【问题标题】:cannot get nested child's data from firebase?无法从 firebase 获取嵌套子节点的数据?
【发布时间】:2019-07-23 08:12:42
【问题描述】:

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

分贝:

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

 });

【问题讨论】:

  • 您确定您传递的 post_id 正确且确实存在吗?
  • 乍一看,代码看起来是正确的。查看应用程序的日志记录输出是否有任何错误。如果这没有帮助,请查看是否可以在 jsbin 或 stackblitz 等工具中重现问题(使用或不使用 Ionic),以便我们查看它。

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


【解决方案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'

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-07-13
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      相关资源
      最近更新 更多