Complete the code to start a transaction in Firebase.
const result = await db.runTransaction(async (transaction) => {
const doc = await transaction.get([1]);
// ...
});The transaction needs a document reference to read data. docRef is the correct variable representing the document.
Complete the code to check if the document exists inside the transaction.
if (!doc.exists) { throw new Error([1]); }
The error message must be a string, so it needs to be in quotes.
Fix the error in the transaction update call to correctly update the document.
transaction.[1](docRef, { count: doc.data().count + 1 });
set which overwrites the whole document.write or modify.The update method updates specific fields in the document without overwriting the whole document.
Fill both blanks to correctly read and update a user's score inside a transaction.
const doc = await transaction.[1](userRef); transaction.[2](userRef, { score: (doc.data().score || 0) + 10 });
set instead of update which overwrites the document.write which is not a valid method.First, you read the document with get. Then, you update the score field with update.
Fill all three blanks to complete a transaction that increments a product's stock count safely.
const productDoc = await transaction.[1](productRef); if (!productDoc.exists) { throw new Error([2]); } transaction.[3](productRef, { stock: productDoc.data().stock + 1 });
set instead of update which overwrites the document.Use get to read the product document, throw an error with a string message if it doesn't exist, then update the stock count.