【问题标题】:How can I traverse through the childs of random id firebase? (NodeJs)如何遍历随机 id firebase 的孩子? (NodeJs)
【发布时间】:2019-10-19 10:44:48
【问题描述】:

我想遍历生成的随机 id 的子值。显然我想检查食物名称是否与请求的名称不匹配。我已经看到了 Java 的解决方案,但无法弄清楚 NodeJs。

这是我尝试过的,但它只返回最随机 id 的 exp_date。

app.intent('getDate',(conv,{foodname})=>{
  return admin.database().ref("/users/${conv.user.id}").once('child_added',function(snapshot){
        conv.ask("${snapshot.val().exp_date}");

  });
});

【问题讨论】:

    标签: node.js firebase firebase-realtime-database dialogflow-es


    【解决方案1】:

    您现在正在将一个侦听器附加到/users/${conv.user.id},它侦听.once('child_added'。所以你的回调被/users/${conv.user.id}下的第一个孩子的快照调用。如果您想让/users/${conv.user.id} 下的所有孩子,您可以执行以下操作:

    app.intent('getDate',(conv,{foodname})=>{
        return admin.database().ref(`/users/${conv.user.id}`).once('value',function(snapshot){
            var msg = '';
            snapshot.forEach(function(child) {
                msg = msg + child.val().exp_date;
            });
            conv.ask(msg);
        });
    });
    

    所以这个:

    1. /users/${conv.user.id} 周围使用文字反引号,因为您使用的是模板字符串。
    2. 监听value 事件,这意味着您会被/users/${conv.user.id} 下的所有子节点的单个快照触发
    3. 使用snapshot.forEach() 循环遍历所有这些匹配的子节点。

    【讨论】:

    • 我使用了 /user/${conv.user.id} 的文字反引号,但由于格式问题,在发布问题时将其删除。无论如何,答案对我有帮助。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-09-04
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多