Hamoonist
Hamoonist

Reputation: 2634

In Firestore how to update a field in a document that may or may not exist?

If we try to update a field in a document in Firestore, it throws an error, that it doesn't exist. Should I manually first check the document exist, and if not, create it and then update the field, or there is a better and more elegant practice?

Upvotes: 15

Views: 6046

Answers (3)

Frank Wang
Frank Wang

Reputation: 431

I wrote a Python code snippet (posted here) that deals with both cases whether the fields exists or not. Reposted here:

key = 'field'
key_nonexistent = 'field_nonexistent'

doc_ref = db.collection('test_coll').document('test_doc')
doc_ref.set({key: False})
# doc_ref.update({key_nonexistent: True})  # Will create 'field_nonexistent' -- not desired

dict_doc = doc_ref.get().to_dict()

if key in dict_doc.keys():
    doc_ref.update(key: True)  # Will update the field only if it exists -- desired

if key_nonexistent in dict_doc.keys():
    doc_ref.update(key_nonexistent: not dict_doc[key_nonexistent])  # Proves the field won't be created if not existent. You can uncomment/comment out the commented line above to see how the result changes

Upvotes: 0

EZH
EZH

Reputation: 73

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)

Upvotes: 3

Doug Stevenson
Doug Stevenson

Reputation: 317710

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.

Upvotes: 12

Related Questions