Firebase count num children of parent [英] Firebase count num children of parent

查看:15
本文介绍了Firebase count num children of parent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 js firebase 中父节点的子节点数.我想要:

I'm trying to get the number of children for a parent node in js firebase. I'd like to have:

'user': {
    '-Yuna99s993m': { count: 1},
    '-Yada99s993m': { count: 2},
}

我正在创建一个云函数,每次进入一个新节点时,它应该添加等于用户节点的 numChildren 的计数.

I'm creating a cloud function witch every time a new node is entered it should add count equal to numChildren of user node.

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

有什么帮助可以让它工作吗?

Any help to get this working?

谢谢.

推荐答案

调用 event.data.ref.parent.numChildren() 不起作用,因为 parentDatabaseReferencenumChildren() 是在 DataSnapshot 上定义的(您可以通过将侦听器附加到引用来获得):

Calling event.data.ref.parent.numChildren() won't work, because parent is a DatabaseReference while numChildren() is defined on DataSnapshot (which you get by attaching a listener to a reference):

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函数示例 Github 存储库中的示例 正是您想要的:保持孩子数量的计数器.该示例使用更有效的方法来保持计数.

There is also a child-count example in the functions-samples Github repo that does precisely what you want: keeping a counter of the number of children. That example uses a more efficient approach for keeping the count.

这篇关于Firebase count num children of parent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆