是否可以仅从Firebase检索密钥列表

Is it possible to only retrieve a list of keys from Firebase?

本文关键字:检索 密钥 列表 Firebase 是否      更新时间:2023-09-26

我有一个如下形式的节点:

index
   $categoryId
     $productId

我希望主要检索index的键的列表,从而检索一个在索引中填充了所有可用$categoryId的对象。

有没有办法在Firebase中检索这个列表?我假设检索密钥列表比从$categoryId检索所有数据的列表更有效。

我知道另一种方法是维护所有类别的索引列表,但这需要更多的编码(当类别被编辑和删除时)。

您可以在REST API中使用浅键选项,但首选索引

Plnker演示

fetch('<my-firebase-app>/category/.json?shallow=true')
  .then((response) => {
    return response.json()
  })
  .then((data) => console.log(data)) // prints only keys under category

不幸的是,在实时SDK中没有解决方案。但是,我建议对数据进行结构化,以避免必须使用RESTneneneba API。尝试在Firebase数据库中存储$categoryId的索引。我知道这是额外的代码,但通常是一行代码。

{
  "lookupCategory": {
    "category_one": true,
    "category_two": true,
    "category_three": true,
    "category_four": true,
    "category_five": true
  }
}

有了这个索引,您就可以进行实时侦听,或者.once()(如果愿意的话)。

var ref = new Firebase('<my-firebase-app>/lookupCategory');
ref.on('value', (snap) => console.log(data));