Aman Chaudhary
Aman Chaudhary

Reputation: 912

How to add an array of maps into cloud firestore dynamically?

I have added data like this,

await firestoreSave.collection('chat').doc().set({
      'buyer_id': "76QlZL2IbADZBnvbofN3",
      'book_id':"N5xlvDcWC5ffwdKWLA6DfF9FcfD2",
      'seller_id': "ranjit",
      "messages": [
        {"message": "What is up", "timeStamp": "Dec 12", "type": userId}
      ]
    }).catchError((onError) {
      print(
          "you have a error");
    });

Now, if I have to just update the messages field. Just add another map with same keys but different values, how would I do that?
I tried using update but I could only figure out adding another field in the previous map but I have to add another map into the array.
How could I do it?

Upvotes: 2

Views: 2846

Answers (1)

osaxma
osaxma

Reputation: 2984

There are two ways to update existing data:

using update(data) which will update the given fields only if the document exists. It'll return an error if the document doesn't exist.

using set(data, SetOptions(merge: true)) will update the given fields and merge them, but also it'll create the document if it doesn't exist.

Now if you'd like to add a value to an array without updating the other fields, you'll have to use FieldValue.arrayUnion with either set or update:

firestoreSave.collection('chat').doc().set({
      "messages": FieldValue.arrayUnion(
        [{"message": "What is up", "timeStamp": "Dec 12", "type": userId}]
      )
    }, SetOptions(merge: true))

Please note, FieldValue.arrayUnion only add unique values and also it doesn't work with nested arrays, which means you'll not be able to use it to update any of the fields inside the message map.

Also as @Renaud mentioned in the comment, you could add multiple values at once too such as:

firestoreSave.collection('chat').doc().set({
          "messages": FieldValue.arrayUnion(
            [{"message": "What is up", "timeStamp": "Dec 12", "type": userId}, 
             {"message": "What's new", "timeStamp": "Dec 12", "type": userId},
            ],
          ),
        }, SetOptions(merge: true))

Upvotes: 5

Related Questions