luxo
luxo

Reputation: 378

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?

Upvotes: 11

Views: 14177

Answers (3)

An Se
An Se

Reputation: 968

Actually, nowadays it is possible. With latest updates db.collection.updateData method actually appends new item to array instead of replacing it. Example usage can be found in Firebase documentation.

If you need to do it manually, you can use

FieldValue.arrayUnion([user.uid])

Upvotes: 9

GIJoeCodes
GIJoeCodes

Reputation: 1850

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

Upvotes: 23

Todd Kerpelman
Todd Kerpelman

Reputation: 17523

Nope. This isn't possible.

Arrays tend to be problematic in an environment like Cloud Firestore where many clients could theoretically append or remove elements from an array at the same time -- if instructions arrive in a slightly different order, you could end up with out-of-bounds errors, corrupted data, or just a really bad time. So you either need to use a dictionary (where you can specify individual keys) or replace the entire array.

Upvotes: 2

Related Questions