Firebase count num children of parent

后端 未结 1 882
眼角桃花
眼角桃花 2021-01-15 01:14

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},
    \'-Yada99s9         


        
相关标签:
1条回答
  • 2021-01-15 01:36

    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.

    0 讨论(0)
提交回复
热议问题