Home  >  Article  >  Web Front-end  >  ## How to Update an Array of Objects in Firestore Without Overwriting the Data?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 12:27:02980browse

## 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()
    })
  });

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

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!

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