'How to count the number of of children for a parent in the new firebase version 9 using numChildren()?

How to count the number of of children for a parent in the new firebase version 9 using numChildren()?

This is how it is done in firebase version 8 below

firebase.database().ref('users/' + userId).on('value', (snapData) => {
      console.log(snapData.numChildren())
    })

But in version 9 this isn't working below

   onValue(ref(db, 'users/'), (snapData) => {
      console.log(snapData.numChildren())
    })

Does anyone know how it is done in firebase version 9 numChildren()?



Solution 1:[1]

Frank got it right, there is no numChildren anymore, but his answer produces an error if there is no value in the db

snapData.val() will be null and you can't Object.keys(null)

so it's:

onValue(ref(db, 'users/'), (snapData) => {
    const count = snapData.exists() && Object.keys(snapData.val()).length || 0;
})

Docs: https://firebase.google.com/docs/reference/js/database.datasnapshot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dima Maryanovsky