Firestore doesn't store two identical values while updating an array

2,635

Solution 1

According to the official documentation regarding updating elements in an array:

arrayUnion() adds elements to an array but only elements not already present.

So there is no way you can add duplicate elements within an array in Cloud Firestore using arrayUnion() function.

To avoid a misunderstanding, however, you can add duplicate elements within an array but only if you read the entire array client side, do the additions (with all duplicates) and then write it back to the database.

Solution 2

You can't use arrayUnion to manage an array that must contain duplicates, as you can tell from the definition of arrayUnion.

What you can do instead is read the document, modify the array in the client to be what you want (including duplicates), and write the array field back to Firestore. You can do this atomically with a transaction.

Share:
2,635
Youssef El Behi
Author by

Youssef El Behi

I love wasting my time on stackoverflow when hope is dead.

Updated on December 11, 2022

Comments

  • Youssef El Behi
    Youssef El Behi over 1 year

    Using flutter, when updating an array with 2 or more consecutive identical values, firestore only adds one.

    Example :

    void updateValue() {
    var now = [new DateTime.now()];
    int pain =5;
     Firestore.instance.collection('Patient').document('bC2ML7LaQ1fWGOl37ZUq').collection('Symptom').document('2H6e99Bvrz6h0HBzgnyg')
                .updateData({ 'nauseaLevel' : FieldValue.arrayUnion([pain]), 'nauseaTime':FieldValue.arrayUnion(now)});
              }
    

    When executing this function 2 times, the array "nauseaLevel" in firestore will only add one "pain" value and ignore the second.

    the array nauseaTime works as expected as the values are different.