3

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
disgra
  • 683
  • 3
  • 6
  • 18

1 Answers1

11

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807