In Firestore how to update a field in a document that may or may not exist?
i just came across this question in 2020 and I must add a usecase to this solution.
in cases of fields with nested maps or arrays the merge option is not a good solution!
for example: I want to update a field that (may) hold the following a map of arrays,
key1: [cell1, cell2, cell3]
key2: [cellA, cellB, cellC]
to the following map:
key1: [cell1, cell2]
using the merge the field at the end will hold the following map:
key1: [cell1, cell2]
key2: [cellA, cellB, cellC]
and NOT just
key1: [cell1, cell2]
if that is the case the best use is just the update function, where you specify the field and the updated value. if not, you'l have to use the SetOption merge option . if this field dosent exist in the document it will create it, and if it does it will update it (at least with android studio and java inside a firestore transaction with my experience)
You haven't said which language you're using to write your code, but each SDK should have an option to pass to set()
that lets you update a document that already exists. For example, in JavaScript on web clients:
doucmentReference.set({ a: 1 }, { merge: true })
That merge: true
will update the data if the document already exists.