每次添加孩子时都会调用最佳Firebase Cloud函数

问题描述

我希望每次将新用户添加到配对对象时都执行一个函数,以增加配对用户数量

exports.onCreateMatchmakingUser = functions.database.ref('/matchmaking/{$uid}').onCreate((snapshot,context) => {
    const currentMatchmakingAmount = snapshot.ref.parent.child('matchmakingAmount').val();
    return snapshot.ref.parent.update({matchmakingAmount: currentMatchmakingAmount+1});
});

我不想获取整个匹配对象,然后获取数字,我只想要matchmatchAmount。 snapshot.ref.parent会带来问题吗(它是否获取了整个匹配对象,或仅获取对它的引用而不下载其数据)?如果可以的话,我该如何解决此问题并编写另一个函数来更新号码而无需不必要的下载?

解决方法

代码中的snapshot.ref.parent.child('matchmakingAmount')不会从数据库中读取任何内容。相反,它仅建立对数据库中matchmakingAmount的引用。您仍然需要使用once("value")明确阅读它:

let amountRef = snapshot.ref.parent.child('matchmakingAmount');
return amountRef.once("value").then((amount) => {
  let currentMatchmakingAmount = amount.val();
  return amountRef.set(currentMatchmakingAmount+1});
});

幸运的是,由于Firebase具有内置的increment运算符,因此如今有一种更简单的方法来执行此操作。这样,以上内容可以归结为:

let amountRef = snapshot.ref.parent.child('matchmakingAmount');
amountRef.set(admin.database.ServerValue.increment(1));

此方法还解决了您的方法中存在的竞争条件:如果两个人几乎同时触发了Cloud Function,则两个写操作可能会互相干扰。通过使用服务器端increment不会发生。

另请参阅:

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...