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

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

Patricia Arquette
Release: 2024-10-25 08:08:02
Original
336 people have browsed it

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

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>
Copy after login

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>
Copy after login

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!

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!