How to update existing document in firestore using set method

I have a firestore document that I want to update. Here’s my code –

                name: userName,
                email: email,
            { merge: true },

I am using “set” method with “merge: true” object. As I want to create a new document if it doesn’t exists and update the data if it exists.

The document that I am trying to update is getting rewritten by new property that I sent, rather than appending the data in the existing document. I read that using {merge: true} will merge the incoming data with current data, but that’s not working. My whole document is being replaced by new data.

Here’s my firestore collection when I first create the document –

enter image description here

And here’s the same document when I update it –

enter image description here


The update() method (or set() with a merge flag) creates a document that:

  1. contains the value for fields that you specify.
  2. any other fields that are already in the document.

So for any field you specify, any existing value for that field in the document will be overwritten.

Given that knowledge, the result is working as expected.

If you want to append the values you specify to the current value of that field, you’ll need to use an atomic transaction to read-and-write the document.

If you want to store multiple username+email combinations, you’ll need to do so in an Array field. You can then either add the new combination with a transaction again, or (if the combination of username+email has to be unique) you can use the atomic array-union operation