Home >Web Front-end >JS Tutorial >How to Update Arrays in Firestore Without Overwriting: A Guide to `arrayUnion` and `arrayRemove`

How to Update Arrays in Firestore Without Overwriting: A Guide to `arrayUnion` and `arrayRemove`

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 08:08:02428browse

How to Update Arrays in Firestore Without Overwriting: A Guide to `arrayUnion` and `arrayRemove`

Effortlessly Updating Arrays in Firestore

When working with Firestore, you may encounter the need to update arrays within documents. While this may seem like a straightforward task, achieving it flawlessly requires an understanding of Firestore's specific capabilities.

Traditionally, attempts to update arrays using techniques like .set() with merge: true or .update() often resulted in overwriting the array's contents. However, Firestore now offers two elegant functions that empower you to seamlessly add and remove array elements:

  • arrayUnion(): Selectively adds elements to an array, ensuring duplicates are avoided.
  • arrayRemove(): Efficiently removes all occurrences of specified elements from an array.

For instance, suppose you have a document with the following structure:

{
  proprietary: "John Doe",
  sharedWith: [
    {who: "[email protected]", when: timestamp},
    {who: "[email protected]", when: timestamp},
  ],
}

To add new entries to the sharedWith array, you can use the following syntax:

<code class="javascript">firebase.firestore()
  .collection('proprietary')
  .doc(docID)
  .update({
    sharedWith: firebase.firestore.FieldValue.arrayUnion(
      {who: "[email protected]", when: new Date()}
    )
  });</code>

Similarly, to remove elements from the array, utilize the following method:

<code class="javascript">firebase.firestore()
  .collection('proprietary')
  .doc(docID)
  .update({
    sharedWith: firebase.firestore.FieldValue.arrayRemove({who: "[email protected]"})
  });</code>

By leveraging these specialized functions, you can confidently update arrays in your Firestore documents without the concern of unwanted overwrites. Remember to refer to the official Firestore documentation for detailed examples and guidance on specific scenarios.

The above is the detailed content of How to Update Arrays in Firestore Without Overwriting: A Guide to `arrayUnion` and `arrayRemove`. 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