使用 GCF/pubsub 更新 Firestore 文档中的计数器

Update counter in a Firestore document with GCF/pubsub

我有一些客户在 PubSub 上发布消息,GCF 触发收到的每条消息,这些消息在我的 Firestore 中编辑文档。该文件有一个 id,一个房间的名称,以及这个房间内的当前人数。 GCF增加当前数量。

但我认为如果同一个房间同时有两条消息,gcf 将无法正常工作并且我的文档中不会有最后的 +2?

基本上,GCF获取文档,并增加当前数量。

如何处理同一房间的多条消息同时到达?

通过使用 FieldValue.increment() you can be sure that the field will be incremented correctly. As explained in this Firebase blog article,“使用 FieldValue.increment(),数据库将立即根据它的任何值进行更改”。

在 Cloud Function for Firebase 中,执行以下操作:

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;
});