0
0
Firebasecloud~5 mins

Transaction read-then-write pattern in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to read data from a database and then update it safely without conflicts. The transaction read-then-write pattern helps you do this by making sure no one else changes the data while you work.
When you want to increase a counter in a database without losing updates from others.
When you need to check a value before changing it, like verifying a balance before withdrawal.
When multiple users might update the same data at the same time and you want to avoid mistakes.
When you want to keep data consistent even if many changes happen quickly.
When you want to retry your update automatically if someone else changed the data first.
Commands
This command runs a transaction that reads the current count from the 'pageViews' document, then increases it by one safely. It ensures no other changes happen during this update.
Terminal
firebase firestore:transaction 'db => db.runTransaction(transaction => {
  return transaction.get(db.collection("counters").doc("pageViews")).then(doc => {
    if (!doc.exists) {
      throw "Document does not exist!";
    }
    const newCount = doc.data().count + 1;
    transaction.update(db.collection("counters").doc("pageViews"), { count: newCount });
  });
})'
Expected OutputExpected
Transaction successfully committed.
This command reads the current value of the 'pageViews' counter to verify the update worked.
Terminal
firebase firestore:get counters/pageViews
Expected OutputExpected
{ "count": 1 }
Key Concept

If you remember nothing else from this pattern, remember: transactions let you read and write data safely together, preventing conflicts.

Common Mistakes
Reading data outside the transaction and then writing inside it.
This can cause conflicts because the data might change between reading and writing.
Always perform both read and write operations inside the same transaction function.
Not handling the case when the document does not exist.
Trying to update a missing document causes errors and failed transactions.
Check if the document exists inside the transaction before updating it.
Summary
Use transactions to read and write data safely in Firebase Firestore.
Run both read and write operations inside the transaction function to avoid conflicts.
Always verify the document exists before updating it in a transaction.