Update "Array of Objects" with Firestore
Firestore provides two methods for updating an array of objects without overwriting the existing data. As mentioned in the reference documentation, you can utilize arrayUnion() and arrayRemove() to achieve this.
Using arrayUnion() to Add Elements
To add new elements to the sharedWith array, you can use arrayUnion(). The following query achieves this:
firebase.firestore() .collection('proprietary') .doc(docID) .update({ sharedWith: firebase.firestore.FieldValue.arrayUnion({ who: "[email protected]", when: new Date() }) });
This query will add the specified element to the sharedWith array if it does not already exist.
Using arrayRemove() to Remove Elements
To remove elements from the sharedWith array, you can use arrayRemove(). The following query achieves this:
firebase. firestore() .collection('proprietary') .doc(docID) .update({ sharedWith: firebase. firestore.FieldValue.arrayRemove({ who: "[email protected]" }) });
This query will remove all instances of the specified element from the sharedWith array.
By utilizing these methods, you can effectively manage arrays of objects in your Firestore database without overwriting the entire collection. Refer to the provided documentation for further details and examples.
The above is the detailed content of ## How to Update an Array of Objects in Firestore Without Overwriting the Data?. For more information, please follow other related articles on the PHP Chinese website!