问题描述
我希望每次将新用户添加到配对对象时都执行一个函数,以增加配对用户的数量。
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
不会发生。
另请参阅: