2

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?

1
  • Another difference between set and update is that the first assumes there's nothing at the given path, so it will not throw an error when there is no pre-existing document, whereas update will. Noticed the previous answers did not mention anything about that, nor about the reason why your code returns different values for each action. Commented Dec 2, 2019 at 20:59

3 Answers 3

7

"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 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this insight. I knew about the merge option. I should have tried it before asking this question but i thought merge is applicable when i have new attributes.
This was important for me on iOS too. I was using .setData and was confused by the behavior, whereas .updateData was the right option. Thanks for the differentiation.
1

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.

Comments

0

FOR Latest version of firebase and flutter

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.