使用firebase for Web检索数据

时间:2016-06-21 10:15:36

标签: javascript firebase firebase-realtime-database

我正在尝试从firebase数据库中检索数据:

firebase.database().ref("/appointments").orderByChild("doctor").equalTo(doctorId).on("value", function(snapshot) {
  var appointmentsData = snapshot.val();
  for(var appointment in appointmentsData) {
    if (!appointmentsData.hasOwnProperty(appointment)) continue;
    var obj = appointmentsData.appointment;
  }
});

如果我在console.log约会或console.log约会数据,我得到正确的值,但如果我console.log约会数据。约定,我得到未定义。

知道如何从firebase返回的对象中检索属性和值吗?

1 个答案:

答案 0 :(得分:3)

您想使用内置Firebase功能的forEach。它允许您遍历快照并轻松获取该对象内每个属性的键和值。它可能是另一个对象或平面值。

firebase.database().ref("/appointments").orderByChild("doctor").equalTo(doctorId).on("value", function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
        // key
        var key = childSnapshot.key;
        // value, could be object
        var childData = childSnapshot.val();
        // Do what you want with these key/values here
        ...
    });
});

参考:

forEach, Firebase 3.0