【问题标题】:Firestore transaction reading a doc that may have not been created yetFirestore 事务读取可能尚未创建的文档
【发布时间】:2021-12-26 00:43:01
【问题描述】:

假设在事务中我将更新一些文档,但是,如果文档不存在,我将创建一个(即,transaction.set())。现在我的问题是,如果文档还没有创建,而其他一些进程调用创建了它,我可以确定事务将被再次调用,这样我就不会丢失数据?

如果文档始终存在,很明显,如果其他进程对其进行写入,则事务将重新启动,但是,如果文档不存在,事务是否会监视它,以便如果它存在在执行过程中创建的是否会启动重新启动?

这是我做交易的方式:

await db.runTransaction(async (transaction) => {
      docRef = db.collection("my_collection").doc("some_id");
      const doc = await transaction.get(sDocRef);

      let initial_data = {}
      if (sDoc.exists)
      {
        initial_update = initial_update({...doc.data()}) //actually only retrieve a subset of fields
      }

      //Some updates on other docs
         ....
         new_data = ....
      await transaction.set(docRef, {...intial_data, ...new_data}, merge=True);

}

【问题讨论】:

    标签: firebase google-cloud-firestore transactions


    【解决方案1】:

    基于此Firebase documentation

    如果文档不存在,则会创建它。如果文档确实存在,则其内容将被新提供的数据覆盖,除非您指定数据应合并到现有文档中。
    如果您不确定文档是否存在,请传递将新数据与任何现有文档合并的选项,以避免覆盖整个文档。

    此外,如果您使用交易,请记住以下几点:

    • 读操作必须先于写操作。
    • 如果并发编辑影响事务读取的文档,则调用事务的函数(事务函数)可能会运行多次。
    • 事务函数不应直接修改应用程序状态。
    • 客户端离线时事务会失败。

    可以在link on updating data with transactionswriting data for React Native Firebase 上找到更多信息。

    【讨论】:

      【解决方案2】:

      是的,我知道这一切,但那不是我问的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-25
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多