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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3