相关疑难解决方法(0)

firestore云函数onCreate/onDelete有时会立即触发两次

我偶尔会在onCreate和onDelete触发器上观察到这种行为. 在此输入图像描述

两个执行都发生在firestore中创建的同一文档中.那里只有一个文档,所以我不明白它是如何触发处理程序两次的.处理程序本身很简单:

module.exports = functions.firestore.document('notes/{noteId}').onCreate((event) => {
  const db = admin.firestore();
  const params = event.params;
  const data = event.data.data();
  // empty
});
Run Code Online (Sandbox Code Playgroud)

这不会一直发生.我错过了什么?

firebase google-cloud-functions google-cloud-firestore

9
推荐指数
1
解决办法
3170
查看次数

如何在云函数中进行幂等聚合?

我正在开发一个Firebase云功能,可以更新我的数据库中某些文档的一些聚合信息.这是一个非常简单的功能,只需将1个文档计数加1即可.与Firestore文档中的示例函数非常相似.

我刚刚注意到,在创建单个新文档时,该函数被调用了两次.请参见下面的屏幕截图,并注意记录的文档ID(iDup09btyVNr5fHl6vif)重复两次:

在此输入图像描述

经过一番挖掘,我发现这个SO帖子说的如下:

目前不保证传递函数调用.随着Cloud Firestore和Cloud Functions集成的改进,我们计划保证"至少一次"交付.但是,在测试期间可能并非总是如此.这也可能导致单个事件的多次调用,因此对于最高质量的函数,确保函数被写为幂等的.

(来自Firestore文档:限制和保证)

这导致我的文档出现问题.如上所述的云函数意味着是幂等的(换句话说,无论函数运行一次还是多次运行,它们改变的数据应该相同).然而,我之前链接的示例函数(对我来说)并不是幂等的:

exports.aggregateRatings = firestore
  .document('restaurants/{restId}/ratings/{ratingId}')
  .onWrite(event => {
    // Get value of the newly added rating
    var ratingVal = event.data.get('rating');

    // Get a reference to the restaurant
    var restRef = db.collection('restaurants').document(event.params.restId);

    // Update aggregations in a transaction
    return db.transaction(transaction => {
      return transaction.get(restRef).then(restDoc => {
        // Compute new number of ratings
        var newNumRatings = restDoc.data('numRatings') + 1;

        // Compute new average …
Run Code Online (Sandbox Code Playgroud)

firebase google-cloud-functions google-cloud-firestore

8
推荐指数
1
解决办法
958
查看次数