Home > Article > Web Front-end > How to Update Arrays of Objects in Firestore Without Overwriting the Entire Array?
Updating Arrays of Objects with Firestore
In Firestore, updating arrays of objects can be a complex task. Here, we tackle the issue and provide a solution that resolves the challenges faced in merging data.
The Problem
Typically, modifying arrays in Firestore requires replacing the entire array. Using the SET method overwrites the array, while the UPDATE method performs the same action. This behavior poses limitations when attempting to update individual elements within an array of objects.
The Solution
Firestore now offers two methods for managing arrays without overwriting the entire array:
To update an array of objects using these methods, follow these steps:
Example Code
<code class="javascript">// Add an element to the "sharedWith" array firebase.firestore() .collection('proprietary') .doc(docID) .update({ sharedWith: firebase.firestore.FieldValue.arrayUnion({ who: "[email protected]", when: new Date() }) }); // Remove an element from the "sharedWith" array firebase.firestore() .collection('proprietary') .doc(docID) .update({ sharedWith: firebase.firestore.FieldValue.arrayRemove({ who: "[email protected]", when: timestamp }) });</code>
By utilizing arrayUnion() and arrayRemove(), you can seamlessly update arrays of objects in Firestore, ensuring that changes are merged into the existing array without overwriting it.
The above is the detailed content of How to Update Arrays of Objects in Firestore Without Overwriting the Entire Array?. For more information, please follow other related articles on the PHP Chinese website!