我想对实时数据库中我想要的字段求平均,然后将它们放在另一个节点上
exports.taverage = functions.database.ref('/User/tsetUser/monthQuit/{pushId}')
.onCreate((snapshot, context) => {
return admin.database().ref('/User/tsetUser/monthQuit/{pushId}/quitTime').once('value')
.then(function(snapshot) {
let sum=0;
snapshot.forEach(child => {
sum = sum + child.val();
})
let avg = sum / snapshot.numChildren();
return admin.database().ref('/User/tsetUser/inform/standardQuit').set(avg);
});
});
错误:Reference.set失败:第一个参数在属性enter image description here中包含NaN
答案 0 :(得分:0)
我的理解是,.numChildren()
实际上应该是in the documentation所述的.getChildrenCount()
。
此外,考虑通过执行以下操作来修改代码以解决“被零除”的情况:
functions.database.ref('/User/tsetUser/monthQuit/{pushId}')
.onCreate((snapshot, context) => {
return admin.database().ref('/User/tsetUser/monthQuit/{pushId}/quitTime').once('value')
.then(function(snapshot) {
/* Get children could via getChildrenCount() */
let divisor = snapshot.getChildrenCount();
/* Ensure divisor is greater than zero to avoid
divide by zero case */
if(divisor > 0) {
let sum=0;
snapshot.forEach(child => {
sum = sum + child.val();
})
let avg = sum / divisor;
return admin.database().ref('/User/tsetUser/inform/standardQuit').set(avg);
}
});
});