Update an Array of Objects in Firestore
Updating an array of objects in Firestore can be a straightforward process, but it requires the use of specific methods in the Firestore SDK.
To append new records to an array of objects, you can use the arrayUnion() method. This method takes an array of elements as its argument and adds those elements to the existing array, but only if they are not already present.
The following code demonstrates how to update the sharedWith array in a document using arrayUnion():
firebase.firestore() .collection('proprietary') .doc(docID) .update({ sharedWith: firebase.firestore.FieldValue.arrayUnion({ who: "[email protected]", when: new Date() }) })
The arrayRemove() method can be used to remove elements from an array. It takes an array of elements as its argument and removes all instances of each given element.
To remove a specific element from the sharedWith array, you can use the following code:
firebase.firestore() .collection('proprietary') .doc(docID) .update({ sharedWith: firebase.firestore.FieldValue.arrayRemove({ who: "[email protected]" }) })
These methods provide a convenient and efficient way to update arrays in Firestore, ensuring that only the specified elements are added or removed, leaving the rest of the array intact.
The above is the detailed content of How to Efficiently Update Arrays of Objects in Firestore?. For more information, please follow other related articles on the PHP Chinese website!