Home > Web Front-end > JS Tutorial > body text

How to Efficiently Update Arrays of Objects in Firestore?

Linda Hamilton
Release: 2024-10-26 05:58:30
Original
768 people have browsed it

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() }) })
Copy after login

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]" }) })
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!