'Firestore fieldvalue.increment using setData does not increment the value, while updateData does

I have an existing document with count value as 1. When i use FieldValue.increment(1) using setData (which should overwrite with new incremented value), it does not increment the value, but using the same with updateData, increments the value to 2.

Why is that? What is the difference between setData and updateData in this case, especially when I am updating with same number of attributes?



Solution 1:[1]

"set" type operations overwrite existing data by default, so it's working the way you expect. It does not consider the values of any existing fields.

If you add the "merge" option to setData, then only the specified fields will get updated, and everything else will stay the same, like update. See the documentation for setData.

ref.setData(data, true)  // merge is true here

Solution 2:[2]

You use setData to set a new value, if it's already set it will just override with the new value without looking at the existing. On the other hand updateData updates the value, just as it should.

Solution 3:[3]

FOR Latest version of firebase and flutter

batch.set(
    SetOptions(merge: true));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Doug Stevenson
Solution 2
Solution 3 Bikash Cocboy