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

后端 未结 1 1934
南笙
南笙 2020-12-18 07:11

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 i

相关标签:
1条回答
  • 2020-12-18 07:45

    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()
    });
    
    0 讨论(0)
提交回复
热议问题