Firebase (2016) 浅层查询

Firebase (2016) Shallow Query

我正在试用 Firebase(自 Google 的新版本)。

在 Firebase 的原始版本中,参数 shallow=true 将 return 一个 object,其中每个 key 在 tree/branch 被请求(因此,而不是 children 被 returned,你只会知道 child(ren) 存在的事实)。这很有用,因为您不一定需要来自 child 个节点的所有数据(特别是如果有很多的话)。

有没有办法用 Google 的新版 Firebase 做到这一点?我在想:

firebase.database().ref('/data/?shallow=true').once('value', function(snapshot) {
  // do something with snapshot
}

上面的代码 snapshot.val() return 是空的,如果我没看错 the docs,这个功能似乎已经消失了。

Firebase 数据库 2.x 中的 ?shallow=true 参数仅在 REST API 中可用。参见 https://www.firebase.com/docs/rest/guide/retrieving-data.html#section-rest-uri-params

在新的 Firebase 数据库 3.x 中,相同的参数仍然只在 REST API 中可用。参见 https://firebase.google.com/docs/database/rest/retrieve-data#shallow

您使用的是 Firebase SDK(从外观上看JavaScript),它从不支持此参数。

有关过去讨论过的更多问题,请参阅:

  • How do I do a shallow query on Firebase iOS?
  • Get Firebase child nodes' names without getting their children too in Firebase response?

根据 Frank 的回答,这对我有用:

import request from 'request';

request({ url: "https://[YOUR-APP-ID].firebaseio.com/path/to/data/.json?shallow=true" }, (error, response, body) => {
    const shallowData = JSON.parse(body);
    console.log(shallowData);
});

参考:https://firebase.google.com/docs/database/rest/retrieve-data#shallow