Firebase count num children of parent

梦想的初衷 提交于 2020-01-21 08:55:47

问题


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},
}

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?

Thank you.


回答1:


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

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.



来源:https://stackoverflow.com/questions/44760645/firebase-count-num-children-of-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!