Complete the code to update a Firestore document only if it exists.
const docRef = firestore.collection('users').doc('user1'); docRef.[1]({ age: 30 })
The update method updates fields only if the document exists, which is key for optimistic concurrency.
Complete the code to perform a transaction that reads and updates a Firestore document atomically.
firestore.runTransaction(async (transaction) => {
const doc = await transaction.[1](docRef);
const newAge = doc.data().age + 1;
transaction.update(docRef, { age: newAge });
});Inside a transaction, get reads the document snapshot to ensure atomicity.
Fix the error in the transaction code to ensure the update only happens if the document exists.
firestore.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
if (doc.exists) {
transaction.[1](docRef, { age: doc.data().age + 1 });
}
});Use update to modify the document only if it exists, preventing accidental creation.
Fill both blanks to implement optimistic concurrency control using Firestore document versioning.
firestore.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
const currentVersion = doc.data().[1];
if (currentVersion === expectedVersion) {
transaction.update(docRef, { age: newAge, [2]: currentVersion + 1 });
} else {
throw new Error('Version mismatch');
}
});Use a version field to track document changes and ensure updates only happen if versions match.
Fill all three blanks to implement a Firestore transaction that safely increments a counter with optimistic concurrency.
firestore.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
const currentCount = doc.data().[1];
const currentVersion = doc.data().[2];
if (currentVersion === expectedVersion) {
transaction.update(docRef, { [1]: currentCount + 1, [2]: currentVersion + 1 });
} else {
throw new Error('Version conflict');
}
});The count field is incremented, and the version field is checked and incremented to ensure safe concurrent updates.