如何使用javaScript在Firebase数据库中检索嵌套的子值?

时间:2017-01-28 12:04:56

标签: javascript firebase firebase-realtime-database

这是我的Fireabse数据库结构。我想检索不是硬编码值的20170116个密钥的数据。这是动态键。我得到了一些键和值,如:

这是我的功能:

function getData(prospectId) {
    database.ref('users/'+prospectId).once('value').then(function(snapshot) {
        var prospectId = snapshot.key ;
        console.log("prospectId : "+ prospectId); // output is : prospectId : 1104812

        snapshot.forEach(function(childSnapshot) {
            var businessUrl = childSnapshot.key;
            console.log("businessUrl : "+ businessUrl); // output is : businessUrl : http:\\www.abc.com
            var dates = Object.keys(childSnapshot.val());
            console.log("dates : "+ dates); //output is : dates : 20170116,20170117,20170119,20170121
            var singleDate = dates[0];
            console.log("singleDate : "+ singleDate); //output is : singleDate : 20170116
        });
    });
}  

getData(1104812);

Here is my Fireabse database structure

那么如何获取20170116日期数据或快照?

1 个答案:

答案 0 :(得分:2)

您正在将值侦听器附加到/users/1104812。因此,您在回调中获得的快照将包含以下内容的子节点:201701162017011720170119

当您循环播放子项时(snapshot.forEach(function(),childSnapshot将依次成为每个节点。

这些节点中没有一个拥有子clientUrldistrictId,这些节点在树中更深一层:

database.ref('users/'+prospectId).once('value').then(function(snapshot) {
  var prospectId = snapshot.key ;

  snapshot.forEach(function(snapshot1) {
    console.log(snapshot1.key); // e.g. "http://..."
    snapshot.forEach(function(snapshot2) {
      console.log(childSnapshot.key); // e.g. "20170116"
      childSnapshot.forEach(function(snapshot3) {
        console.log(grandchildSnapshot.key); // e.g. "-Kb9...gkE"
        console.log(grandchildSnapshot.val().districtId); // "pne"
      });
    });
  });
});
相关问题