将所有Firebase在JS中反驳的numChildren汇总

时间:2019-02-14 16:45:49

标签: javascript firebase firebase-realtime-database

我想获取Firebase返回的numChildren数组的总和,以我为例,它是[1、2、3、4]。我需要将其设置为11,但是我不知道该怎么做。我尝试了sum和reduce函数,但没有结果。在下面,我将代码和一些示例留在控制台中。

const dbRefResenas = firebase.database().ref('Clientes/' + allUserData1.empresa + '/resena/' + 'excelentes/' + dt.getFullYear())
    dbRefResenas.once("value")
    .then(function(snapshot){
        snapshot.forEach(function(childData) {
            childData.forEach(function(childDataItem) {
                childDataItem.forEach(function(childDataItems) {
                    console.log(childDataItems.numChildren());
                })
            })
        })
   })

My db refreshed

My console

1 个答案:

答案 0 :(得分:0)

因为您一次就能获取所有数据,所以实际上非常简单:

const dbRefResenas = firebase.database().ref('Clientes/' + allUserData1.empresa + '/resena/' + 'excelentes/' + dt.getFullYear())
    dbRefResenas.once("value")
    .then(function(snapshot){
        var sum = 0;
        snapshot.forEach(function(childData) {
            childData.forEach(function(childDataItem) {
                childDataItem.forEach(function(childDataItems) {
                    sum = sum + childDataItems.numChildren();
                })
            })
        })
        console.log(sum);
   })

请注意,如果您重复执行此操作,并且不以其他任何方式使用snapshot中的数据,则会浪费大量带宽。您可能希望对数据库中单独节点中的子节点总数进行计数,并在每次数据库写入时对其进行更新。尽管这样写会更复杂,但在这种情况下读取计数会更简单/更便宜。参见child-children sample in the functions-samples repo