Overwrite vs merge difference in Firebase

Viewed 91

From reading the documentation for the set document operation, it seems to me that overwrite and merge mean the same thing which is to replace existing data with new ones. I'm not understanding the difference between the two, even they are phrased to have separate meanings here.

Specifically where it says

If the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document, as follows:

2 Answers

.set(), by default will OVERWRITE any existing document, and will create a document if it does not exist. By default, if you do NOT specify a field in your data, the existing data in that field will be DELETED - the incoming data will become the new DOCUMENT, and all previous fields/data will be lost.

.set() can OPTIONALLY be provided with an object, one field of which is "merge". IF this field exists, and IF it is set to true, the ONLY fields specified in the new data object will be added and/or overwritten. Remember that Firestore documents are effectively Maps, and fieldnames must be unique. New fields will be added; existing fields will be overwritten; fields that are NOT present in the data object will remain - hence "merge".

.update() REQUIRES that the document ALREADY exist, and will fail if it does not. By default, it will ONLY write to the fields specified as arguments to .update()

A set-and-merge will create the document if it doesn't exist, where an update call will fail in that scenario.

There may be more differences that I'm not aware of, but this is my main reason for picking one over the other.

Related