Complete the code to perform an atomic update on a Firestore document.
db.collection('users').doc('user1').[1]({ age: 30 });
The update method performs an atomic update on the document, ensuring consistency.
Complete the code to run a transaction that increments a counter atomically.
db.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
const newCount = doc.data().count + [1];
transaction.update(docRef, { count: newCount });
});Incrementing by 1 is a common atomic operation to increase counters safely.
Fix the error in the transaction code to ensure atomicity.
db.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
const newBalance = doc.data().balance [1] 100;
transaction.update(docRef, { balance: newBalance });
});Subtracting 100 from the balance atomically ensures consistency when deducting funds.
Fill both blanks to atomically increment and check a value in Firestore.
db.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
if (doc.data().stock [1] 0) {
transaction.update(docRef, { stock: doc.data().stock [2] 1 });
}
});The code checks if stock is greater than 0, then subtracts 1 atomically to reduce stock.
Fill all three blanks to atomically update multiple fields in a Firestore document.
db.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
transaction.update(docRef, {
balance: doc.data().balance [1] 50,
points: doc.data().points [2] 10,
status: [3]
});
});The transaction adds 50 to balance, subtracts 10 from points, and sets status to 'active' atomically.