Complete the code to start a transaction in Firebase.
db.runTransaction([1]);The runTransaction method requires a function that defines the transaction operations. This function is passed as an argument.
Complete the code to get a document reference inside a transaction.
const docRef = db.collection('users').doc([1]);
The doc() method requires the document ID, which is usually stored in a variable like userId.
Fix the error in reading data inside the transaction function.
return transaction.get(docRef).then(doc => { if (!doc.exists) { throw new Error('Document does not exist'); } const newCount = doc.data().count [1] 1; transaction.update(docRef, { count: newCount }); });
+= inside an expression causes syntax errors.To increase the count by 1, use the + operator. The += operator cannot be used inside expressions like this.
Fill both blanks to correctly update a field and commit the transaction.
transaction.[1](docRef, { [2]: newValue });
set which replaces the whole document.The update method changes specific fields. Here, the field count is updated with newValue.
Fill all three blanks to complete the transaction function that increments a user's score.
db.runTransaction(async (transaction) => {
const docRef = db.collection('users').doc([1]);
const doc = await transaction.get(docRef);
if (!doc.exists) {
throw new Error('User not found');
}
const newScore = doc.data().[2] [3] 1;
transaction.update(docRef, { score: newScore });
});- or *.The document ID is userId. The field to increment is score, and the operator to add 1 is +.