Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an array item from a nested document in firebase?

I'm working on a Vue,firebase app and I'm saving the userevents in a firebase collection, I update this userevents array when a user schedule an event and want to delete it when the user cancels or remove it,

users(collection) -
 test123(document) -
      "id" . --fields
      "username" . --fields
      "userevents" . --array
         [0]
            "eventid"
            "date"
            "desc"
            "status"
         [1]
            "eventid"
            "date"
            "desc"
            "status"

From UI, if the user cancels an event, I will have the eventid and want to delete it from the userevents array. I tried removing the item from the array using below code, but it is deleting all the items from the userevents,

userRef.update({
    eventid: firebase.firestore.FieldValue.delete()
});

Is there a way to achieve this in firebase?

like image 886
Annette Avatar asked Apr 26 '19 21:04

Annette


People also ask

How can I remove a specific item from an array?

If you want to remove an item from an array, you can use the pop() method to remove the last element or the shift() method to remove the first element.

How do you remove an item from the middle of an array?

You can delete items from the end of an array using pop(), from the beginning using shift(), or from the middle using splice() functions.

How do you add and remove items from an array?

The splice method can be used to add or remove elements from an array. The first argument specifies the location at which to begin adding or removing elements. The second argument specifies the number of elements to remove. The third and subsequent arguments are optional; they specify elements to be added to the array.


1 Answers

Firestore currently doesn't support deleting elements from an array using just a field from an element in that array (in your case, eventid). There are a couple of workarounds:

Method 1

You can use FieldValue.arrayRemove to remove an element from an array by value. The value has to match the whole element in the array, and it will delete all elements in the array that match that value. You can read more about that, and manipulating arrays in general here. Since your array elements are objects, the code would look like this:

userRef.update({
    "userevents": firebase.firestore.FieldValue.arrayRemove({"eventid": ..., "date": ..., "desc":..., "status":...})
});

Method 2

You're currently storing objects inside of an array. What you could do is make userevents a map (an object) instead of an array. Assuming that eventid is unique, you can index the map by eventid and then just delete the entry from the map like this:

userRef.update({
    ['userevents.' + eventid]: firebase.firestore.FieldValue.delete()
});
like image 137
clk Avatar answered Oct 08 '22 08:10

clk