javascript - 在 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;
什么?
这是否提供尚未提交的最新更新?或者它是否给出了之前提交的数据?
感谢你的帮助。
谢谢
解决方案
您将在事务中获得的数据是数据库中的最新数据。那些保存在客户端且未提交到数据库的将不会在事务中。事务确保每个路径只能完成一次写入,因此如果有一个从客户端将数据提交到数据库的过程,您的事务将自动重试,直到下一个写入数据库。很难判断您的交易还是来自其他设备的交易将是第一笔交易。这就是我们进行交易的原因。与他们无关。
推荐阅读
- c - 找到最小时间和日期戳的有效方法是什么?
- jenkins - jenkins 使用无法联系节点名称 java.lang.InterruptedException 构建停滞
- python - 值:要解压的值太多(预计 18 个)
- r - 如何有效地将几列分组为 data.table 中的一个列表列
- angularjs - 我正在做 HTTP POST 以使用 RESTApi 将 .xlsx 文件上传到服务器,但我从服务器收到错误 500 错误
- android - 如何设置完全透明的导航栏(NOT TRANSLUCENT)并不断接收窗口插图更新
- typescript - How to type a function that transforms some properties of an input object
- python - 仅在部分子图中删除了刻度和标签
- dataweave - 使用 datawave 2.0 mule4 在 XML 数组中添加递增的数字?
- android - 尝试在 Android Studio 中构建 Cordova 应用程序时为什么会出现此错误