Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 每次添加子级时调用的最佳Firebase云函数_Node.js_Firebase Realtime Database_Google Cloud Functions - Fatal编程技术网

Node.js 每次添加子级时调用的最佳Firebase云函数

Node.js 每次添加子级时调用的最佳Firebase云函数,node.js,firebase-realtime-database,google-cloud-functions,Node.js,Firebase Realtime Database,Google Cloud Functions,我希望在每次向matchmaking对象添加新用户时执行一个函数,以增加matchmaking用户的数量 exports.onCreateMatchmakingUser = functions.database.ref('/matchmaking/{$uid}').onCreate((snapshot, context) => { const currentMatchmakingAmount = snapshot.ref.parent.child('matchmakingAmoun

我希望在每次向matchmaking对象添加新用户时执行一个函数,以增加matchmaking用户的数量

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

我不想获取整个matchmaking对象,然后获取数字,我只想要matchmakingAmount。
snapshot.ref.parent
是否会导致此问题(它是获取整个matchmaking对象,还是仅获取对它的引用而不下载其数据)?如果是这样,我如何解决这个问题并编写另一个只更新数字而不进行不必要下载的函数?

代码中的
snapshot.ref.parent.child('matchmakingAmount')
不会从数据库中读取任何内容。相反,它只是在数据库中设置对
matchmakingAmount
的引用。您仍然需要使用
一次(“值”)
显式读取它:


幸运的是,现在有一种更简单的方法可以做到这一点,因为Firebase有一个内置的
increment
操作符。综上所述,上述情况归结为:

let amountRef = snapshot.ref.parent.child('matchmakingAmount');
amountRef.set(admin.database.ServerValue.increment(1));
这种方法还解决了您的方法中存在的竞争条件:如果两个人几乎同时触发云函数,那么这两个写操作可能会相互干扰。通过使用不会发生的服务器端
增量

另见:


在实现您编写的第二位代码时,我是否还应该返回amunref.set(admin.database.ServerValue.increment(1));既然set返回了一个承诺?是的。由于写操作是异步的,所以您希望云计算函数在完成之前保持活动状态,为此,您需要将承诺返回给容器。
let amountRef = snapshot.ref.parent.child('matchmakingAmount');
amountRef.set(admin.database.ServerValue.increment(1));