无法从 firebase 获取嵌套子数据?

cannot get nested child's data from firebase?

我正在尝试获取具有特定 ID 的 post 的所有评论。我已经尝试了所有的解决方案,但它从来没有奏效。当我尝试获取 "posts" (1 st level node) 时,同样的方法有效,但嵌套级别不起作用

分贝:

 calculate_post_rating(post_id){

    console.log('this post id: '+post_id);

    let dbref = firebase.database().ref('/user-reviews/'+ post_id + '/');

    dbref.on('child_added', function (data){                

        console.log(data.key); //console is not even printing this, seems like this part is not even executed.

        console.log('rated by user: ' + data.val().rating);

 });

如果您以不同的方式构建数据并避免 key inside key 会更容易:

https://firebase.google.com/docs/database/rest/structure-data#how_data_is_structured_its_a_json_tree

users-reviews: 
 - reviewingUserId 
   - comment: 'Wow'
   - rating: 5
   - subject: 'This may help you out'

代码确实有效,问题是我在循环中调用了另一个函数 "calculate_post_rating(post_id)",如下所示:

那是其中一些跳过了计算的评分。

let dbref = firebase.database().ref('/posts/');

dbref.on('child_added', function (data){                

    console.log(data.key); //console is not even printing this, seems like this part is not even executed.

    console.log('rated by user: ' + data.val().rating);


let final_rating = calculate_rating(data.key); // this is where the expected final rating wasn't looping properly

});

据此我可以得出结论:由于 firebase 函数是异步的,您永远不应该从循环内调用外部函数?