如何仅在Firestore文档中存在字段的情况下(使用Python)更新字段? [英] How to update a field in a Firestore document only if it exists (using Python)?
问题描述
Firestore文档说明您可以使用 doc_ref.update({'key':'value'})
更新文档中的单个字段(如果该字段不存在,则可以创建它"不存在).
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).
问题是:在我的用例中,我如果该字段不存在,我不想创建该字段(宁愿跳过).另外,如果我确实需要创建它,则 doc_ref.set({'key':'value'},merge = True)
将提供我想要的内容.
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.
推荐答案
我在互联网上发现了零个立即可用的答案,并为我自己的用例编写了此Python代码段,并在此与其他人分享重用.
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
这篇关于如何仅在Firestore文档中存在字段的情况下(使用Python)更新字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!