我正在尝试获取 js firebase 中父节点的子节点数。
我想要:
'user': {
'-Yuna99s993m': { count: 1},
'-Yada99s993m': { count: 2},
}
每次输入新节点时,我都会创建一个云函数女巫,它应该添加等于用户节点的 numChildren 的计数。
exports.setCount = functions.database.ref('/user/{userId}').onWrite(event => {
// This doesn't work
const count = event.data.ref.parent.numChildren();
return event.data.ref.update({ count });
});
有什么帮助让这个工作吗?
谢谢你。
最佳答案
调用 event.data.ref.parent.numChildren()
不会工作,因为 parent
是 DatabaseReference
而 numChildren()
定义于 DataSnapshot
(您可以通过将监听器附加到引用来获得):
exports.setCount = functions.database.ref('/user/{userId}').onWrite(event => {
return event.data.ref.parent.once("value", (snapshot) => {
const count = snapshot.numChildren();
return event.data.ref.update({ count });
});
})
还有一个
child-count
example在功能样本 Github 存储库中,它完全符合您的要求:保留 child 数量的计数器。该示例使用更有效的方法来保持计数。
关于javascript - Firebase 计算父级的 num 个子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44760645/