【问题标题】:How to count the number of of children for a parent in the new firebase version 9 using numChildren()?如何使用 numChildren() 在新的 firebase 版本 9 中计算父级的子级数?
【发布时间】:2022-01-25 01:19:31
【问题描述】:

如何使用numChildren()在新的firebase版本9中计算父母的孩子数量?

这就是在下面的 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() 中它是如何完成的?

【问题讨论】:

  • 没有直接的等价物。您必须将快照转换为 val(),检查它是否是具有子对象的 javascript 对象,然后计算该对象的属性。

标签: javascript firebase firebase-realtime-database


【解决方案1】:

v9 中不再有numChildren,但您可以使用“”获得相同的值

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

【讨论】:

    【解决方案2】:

    Frank 说对了,不再有 numChildren,但如果 db 中没有值,他的回答会产生错误

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多