Cloud Firestore merge true not working in NodeJS

Viewed 64

In firestore documentation it says that merge: true is needed if we want to merge data, it doesn't work

Here is my code, which is very similar to the example, it always replaces the old stored value ​​with the new one

async function updateTotal() {
  const update = await db.collection("resources").doc(id).update({ "total": "500"}, { merge: true })
}

I really need it if you have a solution please

1 Answers

As shown on this other answer:

  • set merge will always override the data with the data you pass, while
  • update is specifically designed to give you the possibility to perform a partial update of a document without the possibility of creating incomplete documents that your code isn't otherwise prepared to handle. Please check this answer, as well as this scenario.

This is what nick-w-nick explains in his comment.

This another answer explains better the use case for each option:

  • 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

For the expected result you explained in your comment, you should be using an increment operation, as follows:

You can increment or decrement a numeric field value as shown in the following example. An increment operation increases or decreases the current value of a field by the given amount.

// Atomically increment the population of the city by 50.  
washingtonRef.update({ 
   population: firebase.firestore.FieldValue.increment(50)  
});

See also:

Related