In Cloud Firestore there are three write operations:
1) add
2) set
3) update
In the docs it says that using set(object, {merge: true})
will merge object with existing one.
The same happens when you use update(object)
So what is the difference if any? It seems strange that google will duplicate logic.
The way I understood the difference:
set
without merge will overwrite a document or create it if it doesn't exist yetset
with merge will update fields in the document or create it if it doesn't existsupdate
will update fields but will fail if the document doesn't existcreate
will create the document but fail if the document already existsThere's also a difference in the kind of data you provide to
set
andupdate
.For
set
you always have to provide document-shaped data:With
update
you can also use field paths for updating nested values:Per docs: https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects
Dot notation allows you to update a single nested field without overwriting other nested field. If you update a nested field without dot notation, you will overwrite the entire map field.
As stated above, this replaces entire friends structure.
This does not.
Another difference (extending Scarygami's answer) between "set with merge" and "update", is when working with a nested values.
if you have a document structured like this:
and want to add
{"friend-uid-3" : true}
using this:
db.collection('users').doc('random-id').set({ "friends": { "friend-uid-3": true } },{merge:true})
will result in this data:
however
update
using this:db.collection('users').doc('random-id').update({ "friends": { "friend-uid-3": true } })
will result in this data: