Difference between set with {merge: true} and update

ZuzEL picture ZuzEL · Oct 6, 2017 · Viewed 47.7k times · Source

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.

Answer

Scarygami picture Scarygami · Oct 6, 2017

The way I understood the difference:

  • set without merge will overwrite a document or create it if it doesn't exist yet

  • set with merge will update fields in the document or create it if it doesn't exists

  • update will update fields but will fail if the document doesn't exist

  • create will create the document but fail if the document already exists

There's also a difference in the kind of data you provide to set and update.

For set you always have to provide document-shaped data:

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

With update you can also use field paths for updating nested values:

update({
  'a.b.c': true
})