A. Missing check if document exists before accessing data
B. Using transaction.update instead of transaction.set
C. Not awaiting transaction.update call
D. Incorrect collection name syntax
Solution
Step 1: Check document existence
The code accesses doc.data().stock without verifying if doc.exists, which can cause errors if doc is missing.
Step 2: Confirm other parts
transaction.update is correct for partial update, awaiting update is not needed as transaction methods handle it, and collection name syntax is correct.
Final Answer:
Missing check if document exists before accessing data -> Option A
Quick Check:
Always check doc.exists before data [OK]
Hint: Always check doc.exists before reading data [OK]
Common Mistakes:
Skipping doc.exists check causing runtime errors
Confusing update with set methods
Expecting to await transaction.update explicitly
5. You want to implement a transaction that increments a user's score only if the current score is less than 100. Which of the following code snippets correctly applies the transaction read-then-write pattern to achieve this?
db.runTransaction(async (transaction) => {
const userRef = db.collection('users').doc('user1');
const doc = await transaction.get(userRef);
if (doc.exists && doc.data().score < 100) {
transaction.update(userRef, { score: doc.data().score + 1 });
}
}); correctly checks if the document exists and if the score is less than 100 before updating.
Step 2: Verify update method and logic
It uses transaction.update to increment the score by 1 only when condition is met, preserving existing data.