close

How to update an “array of objects” with Firestore?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to update an “array of objects” with Firestore? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to update an “array of objects” with Firestore ?

  1. How to update an “array of objects” with Firestore ?

    to update an “array of objects” with Firestore addToCart(docId: string, prodId: string): Promise<void> { return this.baseAngularFirestore.collection('carts').doc(docId).update({ products: firestore.FieldValue.arrayUnion({ productId: prodId, qty: 1 }), }); }

  2. How to update an “array of objects” with Firestore ?

    to update an “array of objects” with Firestore addToCart(docId: string, prodId: string): Promise<void> { return this.baseAngularFirestore.collection('carts').doc(docId).update({ products: firestore.FieldValue.arrayUnion({ productId: prodId, qty: 1 }), }); }

Method 1

#Edit (add explanation 🙂 ) say you have an array you want to update your existing firestore document field with. You can use set(yourData, {merge: true} ) passing setOptions(second param in set function) with {merge: true} is must in order to merge the changes instead of overwriting. here is what the official documentation says about it

An options object that configures the behavior of set() calls in DocumentReference, WriteBatch, and Transaction. These calls can be configured to perform granular merges instead of overwriting the target documents in their entirety by providing a SetOptions with merge: true.

you can use this

const yourNewArray = [{who: "[email protected]", when:timestamp}
{who: "[email protected]", when:timestamp}]    


collectionRef.doc(docId).set(
  {
    proprietary: "jhon",
    sharedWith: firebase.firestore.FieldValue.arrayUnion(...yourNewArray),
  },
  { merge: true },
);

hope this helps 🙂

Method 2

addToCart(docId: string, prodId: string): Promise<void> {
    return this.baseAngularFirestore.collection('carts').doc(docId).update({
        products:
        firestore.FieldValue.arrayUnion({
            productId: prodId,
            qty: 1
        }),
    });
}

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment