0 votes
in Google Cloud by
Can you provide an example of when you would use a transaction in Firestore and why it’s necessary?

1 Answer

0 votes
by

A transaction in Firestore is necessary when you need to read and write data within the same operation, ensuring data consistency. For instance, consider a banking application where we’re transferring funds between two accounts. We must decrease one account’s balance while increasing another’s simultaneously. If these operations aren’t atomic, it could lead to inconsistencies like double spending or insufficient deduction.

Here’s an example of how this can be done using Firestore transactions:

let db = firebase.firestore();
db.runTransaction((t) => {
let account1Ref = db.collection('accounts').doc('account1');
let account2Ref = db.collection('accounts').doc('account2');
return t.get(account1Ref).then(doc1 => {
let newAccount1Balance = doc1.data().balance - transferAmount;
t.update(account1Ref, {balance: newAccount1Balance});
return t.get(account2Ref).then(doc2 => {
let newAccount2Balance = doc2.data().balance + transferAmount;
t.update(account2Ref, {balance: newAccount2Balance});
});
});
}).catch(err => console.log('Transaction failure:', err));

Related questions

0 votes
asked Dec 19, 2023 in Google Cloud by GeorgeBell
0 votes
asked Dec 20, 2023 in Google Cloud by GeorgeBell
...