Home >Web Front-end >JS Tutorial >How to Efficiently Update Arrays of Objects in Firestore?

How to Efficiently Update Arrays of Objects in Firestore?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 05:58:30846browse

How to Efficiently Update Arrays of Objects in Firestore?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn