简体   繁体   中英

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() ?

There is no numChildren anymore in v9, but you can get the same value with"

onValue(ref(db, 'users/' + snapData), (snap) => {
  console.log(Object.keys(snapData.val()).length) // 👈
})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM