Increment counter with Cloud Functions for Firebase
If you want to safely increment a number in a document, you can use a transaction. The following code is taken directly from the linked page. It adds one to a field called population
in a document /cities/SF
after giving it some initial values:
// Initialize document
var cityRef = db.collection('cities').doc('SF');
var setCity = cityRef.set({
name: 'San Francisco',
state: 'CA',
country: 'USA',
capital: false,
population: 860000
});
var transaction = db.runTransaction(t => {
return t.get(cityRef)
.then(doc => {
// Add one person to the city population
var newPopulation = doc.data().population + 1;
t.update(cityRef, { population: newPopulation });
});
}).then(result => {
console.log('Transaction success!');
}).catch(err => {
console.log('Transaction failure:', err);
});
Bear in mind that Firestore is limited to one write per second under sustained load, so if you're going to be writing a lot, you will need to use a sharded counter instead.
There is now a much simpler way to increment/decrement a field in a document: FieldValue.increment()
. Your sample would be something like this:
const FieldValue = require('firebase-admin').firestore.FieldValue;
var chainCounterRef = db.collection('counters').doc('chains');
chainCounterRef.update({ count: FieldValue.increment(1) });
See:
- Incrementing Values Atomically with Cloud Firestore