简体   繁体   中英

runTransaction in Firestore

I am working on a application where Firestore is being used to store the data of the user.

As we know the data write to the Firestore document is not real time causing a problem when write frequency is higher.

So I am planning to use the runTransaction feature in Firestore.
As per the official documentation given here , seems like use of runTransaction would help in handling this concurrent writes.

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; ?
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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