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

## How to Update an Array of Objects in Firestore Without Overwriting the Data?

Barbara Streisand
Release: 2024-10-25 12:27:02
Original
1051 people have browsed it

## How to Update an Array of Objects in Firestore Without Overwriting the Data?

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

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

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!

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