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

问题描述 投票:0回答:2

我正在尝试使用特定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);

 });
javascript firebase ionic-framework firebase-realtime-database ionic2
2个回答
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'

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函数是异步的,你永远不应该在循环中调用外部函数?

© www.soinside.com 2019 - 2024. All rights reserved.