Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore: Append/Remove items from document array

I am trying to append/remove items from an array inside of a Firestore Document but every time the entire array is replaced instead of the new value being appended. I have tried both of the following:

batch.setData(["favorites": [user.uid]], forDocument: bookRef, options: SetOptions.merge())

batch.updateData(["favorites": [user.uid]], forDocument: bookRef)

I know that instead of an array I can use an object/dictionary but that would mean storing additional data that is irrelevant (such as the key), all I need is the ID's stored inside the array. Is this something that is currently possible in Firestore?

like image 660
luxo Avatar asked Oct 25 '17 22:10

luxo


People also ask

How do I remove items from firestore?

To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them. If you have larger collections, you may want to delete the documents in smaller batches to avoid out-of-memory errors.

How do I remove a field from a document in firestore?

To delete a field from a Firestore document, call the deleteField() method as a value of it.

Can I add to an array firestore?

Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, dates, null, and nested arrays and objects.


1 Answers

Update elements in an array

If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present. arrayRemove() removes all instances of each given element.

let washingtonRef = db.collection("cities").document("DC")

// Atomically add a new region to the "regions" array field.
washingtonRef.updateData([
    "regions": FieldValue.arrayUnion(["greater_virginia"])
])

// Atomically remove a region from the "regions" array field.
washingtonRef.updateData([
    "regions": FieldValue.arrayRemove(["east_coast"])
])

See documentation here

like image 98
GIJoeCodes Avatar answered Oct 24 '22 16:10

GIJoeCodes