Firebase查询数组或带有Javascript的对象

时间:2018-11-21 17:29:09

标签: javascript database firebase firebase-realtime-database

我整天都在努力创建Firebase查询!

以下查询从我的Firebase实时数据库中以数组形式返回数据:

exports.getCountry = () => {
  return database
    .ref("/countries")
    .once("value")
    .then(data => data.val());
};

这将从数据库中以对象数组

的格式返回以下内容
[
    {"id":1, "country":"singapore", "population":15000000},
    {"id":2, "country":"hongkong", "population":12000000},
    {"id":2, "country":"vietnam", "population":2250000}
]

但是我想查询数据库以仅返回一条记录,类似

exports.getCountry = () => {
  return database
    .ref("/countries")
    .where('id'===1)
    .once("value")
    .then(data => data.val());
};

将从数据库中返回一行:

{"id":1, "country":"singapore", "population":15000000}

但是我无法使它正常工作!这应该很简单,但是我打不起来!

1 个答案:

答案 0 :(得分:1)

我在复杂查询中引用了these Firebase docs

将它们提供的示例放在一起,我认为您的查询应类似于:

var ref = db.ref("countries");

ref.orderByChild("id").equalTo(1).on("value", function(snapshot) {
    snapshot.forEach( data => {
        console.log(data.val());
    });
});

*未测试

编辑:

我链接的文档是到admin SDK的,如果您使用JavaScript在前端进行此操作,它仍然可以正常工作。 JavaScript SDK似乎具有相同的查询结构-也显示在these docs for the JS SDK中。