我怎样才能遍历随机 id firebase 的孩子? (节点)

How can I traverse through the childs of random id firebase? (NodeJs)

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

这是我试过的方法,但它只是 returns 最随机 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}");

  });
});

您现在正在将侦听器附加到 /users/${conv.user.id},以侦听 .once('child_added'。因此,您的回调将使用 /users/${conv.user.id} 下第一个 child 的快照调用。如果你想获得 /users/${conv.user.id} 下的所有 children,你可以这样做:

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. 下的所有 child 节点的单个快照触发
  4. snapshot.forEach().
  5. 遍历所有这些匹配的 child 节点