首页 > 解决方案 > 在 Firestore 中运行事务

问题描述

我正在开发一个使用 Firestore 存储用户数据的应用程序。

正如我们所知,写入 Firestore 文档的数据不是实时的,当写入频率较高时会导致问题。

所以我打算runTransaction在 Firestore 中使用该功能。
根据此处给出的官方文档,似乎使用runTransaction将有助于处理这种并发写入。

以下是官方文档中给出的示例的修改版本:

// Initialize document
const studentRef = db.collection('Student').doc('stud1');
await studentRef.set({
  name: 'New Name',
  id: 'stud11X',
  present: false,
});
UpdateStudentData: async function () {
  try {
    await db.runTransaction(async (t) => {
      const doc = await t.get(studentRef);
      const isPresent = doc.data().present;
      t.update(studentRef, {population: true});
    });

    console.log('Transaction success!');
  } catch (e) {
    console.log('Transaction failure:', e);
  }
}

我的问题是,例如,如果我们尝试在数据已经在进行中但尚未提交时更新数据,那么 ? 的输出是const isPresent = doc.data().present;什么?
这是否提供尚未提交的最新更新?或者它是否给出了之前提交的数据?

感谢你的帮助。

谢谢

标签: javascriptnode.jsfirebasegoogle-cloud-firestore

解决方案


您将在事务中获得的数据是数据库中的最新数据。那些保存在客户端且未提交到数据库的将不会在事务中。事务确保每个路径只能完成一次写入,因此如果有一个从客户端将数据提交到数据库的过程,您的事务将自动重试,直到下一个写入数据库。很难判断您的交易还是来自其他设备的交易将是第一笔交易。这就是我们进行交易的原因。与他们无关。


推荐阅读