如何从Firebase数据库中选择JSON对象?

时间:2016-12-22 12:49:59

标签: javascript firebase firebase-realtime-database

firebase structure

我有一个如下所示的Firebase结构。我想将消息作为返回的对象。要在SQL中执行此操作,如

select messages from HukMesssage

我该怎么做?

有人可以帮助我如何将SQL更改为Firebase查询吗?

我的json文件如下所示

{
    "HukMessages":
        [
            {
                "To": 1,
                "From": 2,
                "messages": [
                        {
                          "name": "'Venkman'",
                          "message": "'You on your way?'",
                          "face": "'img/venkman.jpg'"
                        }, 
                        {
                          "name": "'Felix He'",
                          "message": "'Ionic comes with a set of colors to start with, but as a general rule colors are meant to be overridden. '",
                          "face": "'img/felix.jpg'"
                        }
                ]
            }
           ]
}

1 个答案:

答案 0 :(得分:0)

对Firebase数据库执行查询时,可能会有多个结果。因此快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。

您的代码需要处理该列表。类似的东西:

var query = firebase.database().ref().child("HukMessages").orderByChild(‌​"From").equalTo('2')‌​; 
query.once("value", function(snapshot) {
  console.log(snapshot.key); // this will print HukMessages, because that's the location you queried

  snapshot.forEach(function(child) {
    console.log(child.key); // this will print the key of a message
  });
});