Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestoregoogle-cloud-functionsgoogle-cloud-pubsub

Update counter in a Firestore document with GCF/pubsub


I have clients who publish messages on a PubSub, and a GCF triggered each message received, which edit a document in my firestore. The document has an id, name of a room, and the current number of people inside this room. The GCF increases the current number.

But I think that if there are two messages for the same room at the same time, the gcf won't do the right job and i won't have the final +2 on my document ?

Basically, the GCF gets the document, and increases the current number.

How could I do to handle the multiple messages arriving at the same time for the same room ?


Solution

  • By using FieldValue.increment() you can be sure that the field will be incremented correctly. As explained in this Firebase blog article, "with FieldValue.increment(), the database would instantly make the change based on whatever value it has".

    In a Cloud Function for Firebase, do as follows:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    
    const FieldValue = require('firebase-admin').firestore.FieldValue;
    
    
    exports.scheduledFunction = functions.pubsub.schedule('...').onRun(async (context) => {
      // ...
      await admin.firestore().collection("...").doc("...").update({ nbrOfPeople: FieldValue.increment(1) });
      // ...
      return null;
    });