简体   繁体   English

Firestore 中的 runTransaction

[英]runTransaction in Firestore

I am working on a application where Firestore is being used to store the data of the user.我正在开发一个使用 Firestore 来存储用户数据的应用程序。

As we know the data write to the Firestore document is not real time causing a problem when write frequency is higher.正如我们所知,写入 Firestore 文档的数据不是实时的,当写入频率较高时会导致问题。

So I am planning to use the runTransaction feature in Firestore.所以我打算在 Firestore 中使用runTransaction功能。
As per the official documentation given here , seems like use of runTransaction would help in handling this concurrent writes.根据此处给出的官方文档,使用runTransaction似乎有助于处理这种并发写入。

Below is the modified version of the example given in the official documentation:以下是官方文档中给出的示例的修改版本:

// 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);
  }
}

My question is that, for example if we try to update the data when one is already in progress and has not committed yet, what is the output of the const isPresent = doc.data().present;我的问题是,例如,如果我们尝试在数据已经在进行中并且尚未提交时更新数据,那么const isPresent = doc.data().present;的输出是什么const isPresent = doc.data().present; ? ?
Does this gives the latest update which is not committed yet?这是否提供了尚未提交的最新更新? Or does it give the previous committed data?或者它是否提供了以前提交的数据?

Appreciate your help.感谢您的帮助。

Thank you谢谢

The data you will get in the transaction is the latest on on the database.您将在事务中获得的数据是数据库中的最新数据。 Those saved on the client side and not commited to the database won't be in the transaction.那些保存在客户端且未提交到数据库的内容将不会出现在事务中。 The transactions ensure that only one write per path can be done so if there is a process of committing the data to the database from a client your transaction will retry automaticaly until it's the next one to write to the database.事务确保每个路径只能写入一次,因此如果存在从客户端将数据提交到数据库的过程,您的事务将自动重试,直到下一个写入数据库。 It's hard to tell if your transaction or the one from the other device will be first.很难判断是您的交易还是来自其他设备的交易会是第一个。 That is the reason why we have the transactions.这就是我们进行交易的原因。 With them it should not matter.和他们在一起应该没关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM