在Firestore中,如何更新可能存在或不存在的文档中的字段?

时间:2018-10-22 16:21:16

标签: firebase google-cloud-firestore

如果我们尝试更新Firestore中文档中的字段,则会引发错误,提示该错误不存在。 我应该手动检查文档是否存在,如果不存在,请创建该文档,然后更新字段,还是有更好,更优雅的做法?

3 个答案:

答案 0 :(得分:2)

您尚未说明要使用哪种语言编写代码,但是每个SDK都应具有一个传递给set()的选项,使您可以更新已经存在的文档。例如,在Web客户端上的JavaScript中:

doucmentReference.set({ a: 1 }, { merge: true })

如果文档已存在,则merge: true将更新数据。

答案 1 :(得分:0)

我只是在2020年遇到了这个问题,我必须在此解决方案中添加一个用例。

对于带有嵌套地图或数组的字段,合并选项不是一个好的解决方案!

例如: 我想更新一个(可能)包含以下数组映射的字段,

key1: [cell1, cell2, cell3]
key2: [cellA, cellB, cellC]

到以下地图:

key1: [cell1, cell2]

使用合并字段,将保留以下地图:

key1: [cell1, cell2]
key2: [cellA, cellB, cellC]

而不仅仅是

key1: [cell1, cell2]

如果是这种情况,最好的用途就是更新功能,您可以在其中指定字段和更新的值。如果不是,则必须使用SetOption merge选项。 如果该字段在文档中存在,它将创建它,如果确实存在,它将更新它(至少以我的经验,至少在firestore事务中使用android studio和java)

答案 2 :(得分:0)

我编写了一个 Python 代码片段(发布在 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