Firebase函数document.create和user.create触发多次触发 [英] Firebase function document.create and user.create triggers firing multiple times

查看:53
本文介绍了Firebase函数document.create和user.create触发多次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图跟踪集合中的文档数量以及Firebase项目中的用户数量.我设置了一些.create触发器以使用增量来更新统计文档,但有时.create函数会为单个创建事件触发多次. Firestore文档和新用户都会发生这种情况.有什么想法吗?

I'm trying to keep track of the number of documents in collections and the number of users in my Firebase project. I set up some .create triggers to update a stats document using increment, but sometimes the .create functions trigger multiple times for a single creation event. This happens with both Firestore documents and new users. Any ideas?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firestore = require('@google-cloud/firestore')
admin.initializeApp();

const db = admin.firestore()

/* for counting documents created */
exports.countDoc = functions.firestore
  .document('collection/{docId}')
  .onCreate((change, context) => {
    const docId = context.params.docId
    db.doc('stats/doc').update({
      'docsCreated': firestore.FieldValue.increment(1)
    })
    return true;
  });

/* for counting users created */
exports.countUsers = functions.auth.user().onCreate((user) => {
  db.doc('stats/doc').update({
    'usersCreated': firestore.FieldValue.increment(1)
  })
  return true;
});

谢谢!

推荐答案

对于如何实现功能的幂等,有一些建议.

There is some advice on how to achieve your functions' idempotency.

FieldValue.arrayUnion()& FieldValue.arrayRemove()函数可安全删除数组中的元素并将其添加到数组中,如果删除的元素不存在,则不会出现重复或错误.

There are FieldValue.arrayUnion() & FieldValue.arrayRemove() functions which safely remove and add elements to an array, without duplicates or errors if the element being deleted is nonexistent.

您可以在文档中创建名为用户"和文档"的数组字段,并通过触发函数使用FieldValue.arrayUnion()在其中添加数据.通过这种方法,您可以通过获取users& docs字段并在其上调用.size().

You can make array fields in your documents called 'users' and 'docs' and add there data with FieldValue.arrayUnion() by triggered functions. With that approach you can retrieve the actual sizes on the client side by getting users & docs fields and calling .size() on it.

这篇关于Firebase函数document.create和user.create触发多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆