Reputation: 1753
I'm having issues implementing a counter using the firestore DB. I have a collection of documents where the document has a field that is updated at some point.
Collection Object Field:true Object Field:false Object Field:true
I need to count all the fields where the value is equals to true. The app is updated from multiple devices at the same time.
How can I accomplish this? Do I need to use the distributed counters approach o just with a cloud function would be enough
Upvotes: 1
Views: 3720
Reputation: 151
Use cloud functions. simple example:
// database in the 'posts' collection
{
title: "My great post",
categories: {
"technology": true,
"opinion": false,
"cats": true
}
Cloud functions script:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
const docRef = admin.firestore().collection('post')
.where('categories', '==', true)
.get()
.then((result) => {
res.send(result.size()); //return the count
}).catch(function(error){
console.log("got an error",error);
})
exports.countFunction = functions.https.onRequest(...);
Upvotes: 1
Reputation: 4898
Cloud Firestore has a limit of one write per document/second. I would not advise having multiple users writing to the same document at the same time. You should definitely use the Distributed Counters method.
Upvotes: 1