如何使用 numChildren() 计算新 firebase 版本 9 中 parent 的 children 的数量?

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

如何使用 numChildren() 在新的 firebase 版本 9 中计算 parent 的 children 的数量?

下面的 firebase 版本 8 是这样做的

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

但在第 9 版中,这在下面不起作用

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

有谁知道在 firebase 版本 9 中是如何完成的 numChildren()

v9 中不再有 numChildren,但您可以使用

获得相同的值
onValue(ref(db, 'users/'), (snapData) => {
  console.log(Object.keys(snapData.val()).length) // 
})

Frank 做对了,不再有 numChildren,但如果数据库中没有值,他的回答会产生错误

snapData.val() 将为空,您不能 Object.keys(null)

所以是:

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

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