0

I want to add a new field in a array but when i try to add a new field it will remove rest and add only the remaining one. i tried this but not working

 collectionRef
        .doc("userIdLalit")
        .collection("stories")
        .doc("BHUCC3ewEeByJ6U68ygJ")
        .update(
      {
        "reactionModel": {
          "user": [
            {"fourth element": "Sam"},
          ],
        }
      },
    );

This code will remove the 0th and 1st element and add the fourth element but i want all of them whenever i add a new field

I tried with set method with merge true but didnt work

enter image description here

Lalit Rawat
  • 1,022
  • 2
  • 17
  • 39

1 Answers1

2

You can use FieldValue.arrayUnion() to push a new item to the array:

collectionRef
  .doc("userIdLalit")
  .collection("stories")
  .doc("BHUCC3ewEeByJ6U68ygJ")
  .update({
    "reactionModel.user":  FieldValue.arrayUnion({"fourth element": "Sam"})
  });

Also the array is nested in a map so you would have to use dot notation to update it i.e. "reactionModel.user".

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84