Complete the code to initialize a distributed counter document reference in Firebase.
const counterRef = firestore.collection('counters').doc([1]);
The document ID 'distributedCounter' clearly identifies the counter document in the 'counters' collection.
Complete the code to increment a shard's count atomically using a transaction.
await firestore.runTransaction(async (transaction) => {
const shardRef = counterRef.collection('shards').doc([1]);
const shardDoc = await transaction.get(shardRef);
if (!shardDoc.exists) {
transaction.set(shardRef, { count: 1 });
} else {
transaction.update(shardRef, { count: shardDoc.data().count + 1 });
}
});Using 'shard0' as the shard document ID is a common pattern to identify one shard among many.
Fix the error in the code to correctly sum counts from all shards.
const shardsSnapshot = await counterRef.collection('shards').get(); let totalCount = 0; shardsSnapshot.forEach(doc => { totalCount += doc.data().[1]; });
The field storing the count in each shard document is named 'count'.
Fill both blanks to create a function that initializes shards with zero counts.
async function initializeShards(counterRef, numShards) {
const batch = firestore.batch();
for (let i = 0; i < numShards; i++) {
const shardRef = counterRef.collection('shards').doc([1]);
batch.set(shardRef, { [2]: 0 });
}
await batch.commit();
}The shard document IDs use template literals like `shard${i}` to create unique shard names. The count field is named 'count' and initialized to 0.
Fill all three blanks to implement a function that reads and sums counts from all shards.
async function getDistributedCount(counterRef) {
const shardsSnapshot = await counterRef.collection([1]).get();
let totalCount = 0;
shardsSnapshot.forEach(doc => {
totalCount += doc.data()[[2]];
});
return totalCount;
}
const count = await getDistributedCount([3]);The function reads from the 'shards' collection, sums the 'count' field from each shard, and is called with the counterRef.