Nicolas O
Nicolas O

Reputation: 151

Firebase - Add Value to Array which already exists

How can I add a value to an array in Firebase IF (!!) this value already exists in the array?

In the documentation I could only find the arrayUnion method, however, this checks if the value is already in the array and only adds it if this is not the case.

In particular, I have the following Flutter code:

Future logCount () async {
    return await collection.document(id).setData({
      'counts': FieldValue.arrayUnion([count]),
    });
  }

Do you know how to change this code or what I could use to not run into this problem with arrayUnion? I could not find something suitable in the documentation.

Thanks for your help!

Upvotes: 0

Views: 724

Answers (1)

Ali Bayram
Ali Bayram

Reputation: 7921

You can fetch the document and add your item to the array and update your remote document;

Future logCount() async {
  DocumentSnapshot ds = await collection.document(id).get();
  List counts = ds.data['counts'];
  counts.add(count);

  return await collection.document(id).updateData({'counts': counts});
}

Upvotes: 2

Related Questions