无法从Firebase获取嵌套的孩子的数据?

时间:2019-03-01 10:00:21

标签: javascript firebase ionic-framework firebase-realtime-database ionic2

我正在尝试获取具有特定ID的帖子的所有评论。我已经尝试了所有解决方案,但它永远无法正常工作。当我尝试获取“帖子”(第一个级别节点)时,相同的方法有效,但是嵌套级别不起作用

db: enter image description here

 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);

 });

2 个答案:

答案 0 :(得分:1)

如果您以不同的方式构造数据并避免在密钥内使用密钥,则会更容易:

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'

答案 1 :(得分:0)

代码实际上正在工作,问题是我正在循环中调用另一个函数"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函数是异步的,因此您永远不应从循环内部调用外部函数?