Firebase 计数父级的子级
Firebase count num children of parent
我正在尝试获取 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 });
});
})
functions-samples Github 存储库中还有一个 child-count
example 可以精确地执行您想要的操作:保留子项数量的计数器。该示例使用更有效的方法来保持计数。
我正在尝试获取 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 });
});
})
functions-samples Github 存储库中还有一个 child-count
example 可以精确地执行您想要的操作:保留子项数量的计数器。该示例使用更有效的方法来保持计数。