How to update a field in a Firestore document only if it exists (using Python)?
Asked Answered
M

1

0

Firestore documentation explains you can use doc_ref.update({'key': 'value'}) to update a single field in a document (and create it if that field doesn't exist).

The problem is: in my use case I don't want to create that field if it doesn't exist (would rather skip). Also if I do need to create it, doc_ref.set({'key': 'value'}, merge=True) will give what I want.

Margit answered 20/4, 2021 at 23:20 Comment(0)
M
0

I found zero ready-to-use answer on the internet and wrote this Python code snippet for my own use case, and I'm sharing here for others to reuse.

Please read the comment to see how it works:

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
Margit answered 20/4, 2021 at 23:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.