Home > Software design >  How to do batched transactions in firestore?
How to do batched transactions in firestore?

Time:11-06

After a few searches, it appears that it is impossible to run batched transactions.

What I want to achieve:

  • I have an app that tracks transactions.
  • I need to display both the monthly and overall spending/earnings, so I need to keep a tally of them.
  • What this means is that I need to run 3 operations simultaniusly: add the transaction to the transaction collection, update the overall tally and update the monthly tally

How do I update both the overall and monthly spending/earnings to keep consistency?

Is there really no way of running batched transactions? If so, what's the next best solution?

CodePudding user response:

I need to run 3 operations simultaniusly: add the transaction to the transaction collection, update the overall tally and update the monthly tally

As Tim mentioned in his comment you need to use a Transaction since you want to first read the monthly and total docs before updating them (and create the transaction doc) in an atomic manner.

Something along the following lines:

import { runTransaction } from "firebase/firestore";

try {
    const newTransactionDocRef = ...;
    const amount = ...,
    const monthlyDocRef = ...;
    const totalDocRef = ...;
    await runTransaction(db, async (transaction) => {
        const monthlyDoc = await transaction.get(monthlyDocRef);
        const totalDoc = await transaction.get(totalDocRef);
        
        transaction.set(newTransactionDocRef, {...});
        const newMonthlyTally = monthlyDoc.data().total   amount;
        transaction.update(monthlyDocRef, { total: newMonthlyTally });
        const newTotalTally = totalDoc.data().total   amount;
        transaction.update(totalDocRef, { total: newTotalTally });
    });
    console.log("Transaction successfully committed!");
} catch (e) {
    console.log("Transaction failed: ", e);
}

Note that you need to initiate the monthly and total docs.

  • Related