0

Imagine that I have the following document stored in my Firestore.

collection: "myColection"
  document: "myDocument"
    fields:
      someBoolean: true
      someArray: ['a','b','c']
      etc

Firebase DOCS - Source

QUESTION

What's the difference between doing the following methods to toggle the someBoolean field:

OPTION 1

const docRef = db.collection('myCollection').doc('myDocument');

await docRef.set({
  someBoolean: false
  }, 
{merge: true});

OPTION 2

const docRef = db.collection('myCollection').doc('myDocument');

await docRef.update({
  someBoolean: false
});
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

4 Answers4

1

If you already have the myDocument document stored in the myCollection collection there will be no difference.

The difference will appear if there is no existing myDocument document: set() will work but not update().

See the doc https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#update, which says "The update will fail if applied to a document that does not exist."

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
1

You can find the answer on Difference between set with {merge: true} and update

In short, set with merge will create the new fields/document if they dont exist while update will fail if the document dont exist.

Also the update function work differently for nested values. It will replace the nested object while set will merge the new value with the current one.

Alejandro Barone
  • 1,743
  • 2
  • 13
  • 24
1
  • set, overwrites a document or create if it cannot find it

  • set with { merge: true } will update fields in the document or create if it cannot find it

  • update will update fields but will throw an error if the document doesn't exist

One important detail, with set you have to provide the path:

set({ foo: { bar: { baz: true } } }, { merge: true })

Update, this is enough

update({
  'foo.bar.baz': true
})
andresmijares
  • 3,658
  • 4
  • 34
  • 40
0

An update will fail if the document doesn't exist.

Ace
  • 1,028
  • 2
  • 10
  • 22