【问题标题】:In Firestore how to update a field in a document that may or may not exist?在 Firestore 中,如何更新文档中可能存在或不存在的字段?
【发布时间】:2019-03-26 18:53:30
【问题描述】:

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

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      到以下地图:

      key1: [cell1, cell2]
      

      使用最后的合并字段将保存以下地图:

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

      不只是

      key1: [cell1, cell2]
      

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

      【讨论】:

        【解决方案3】:

        我编写了一个 Python 代码 sn-p(发布于 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
        

        【讨论】:

          猜你喜欢
          • 2022-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-24
          • 2022-11-18
          • 1970-01-01
          • 2021-12-14
          • 1970-01-01
          相关资源
          最近更新 更多