The difference between installing with {merge: true} and updating

Cloud Firestore has three write operations:

1) add

2) install

3) update

The docs say that using set(object, {merge: true}) will merge the object with the existing one.

The same thing happens when using update(object) So what's the difference, if any? It seems strange that google will duplicate the logic.

+7
database firebase google-cloud-firestore
source share
2 answers

As I understand the difference:

  • set without merging will overwrite the document or create it if it does not already exist

  • set with merge will update fields in the document or create it if it does not exist

  • update will update the fields, but will not work if the document does not exist

  • create will create the document but will not work if the document already exists

There is also a difference in the kind of data that you provide set and update .

For set you always need to provide data in the form of a document:

 set( {a: {b: {c: true}}}, {merge: true} ) 

With update you can also use field paths to update nested values:

 update({ 'abc': true }) 
+16
source share

Another difference (extension of Scarygami's answer) between "set with merge" and "update" is work with nested values.

if you have a document structured as follows:

  { "friends": { "friend-uid-1": true, "friend-uid-2": true, } } 

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 the following data:

  { "friends": { "friend-uid-1": true, "friend-uid-2": true, "friend-uid-3": true } } 

however update using this:

db.collection('users').doc('random-id').update({ "friends": { "friend-uid-3": true } })

will result in the following data:

  `{ "friends": { "friend-uid-3": true } }` 
+8
source share

All Articles