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

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

我有一个这种形式的节点:

index
   $categoryId
     $productId

我希望主要检索 index 的键列表,因此是一个包含索引中所有可用 $categoryId 的对象。

有没有办法在 Firebase 中检索此列表?我假设检索键列表比检索包含 $categoryId 中所有数据的列表更有效。

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

您可以在 REST API 中使用 shallow keys option,但首选索引。

Plnker demo.

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

很遗憾,实时 SDK 中没有解决方案。但是,我建议构建您的数据以避免必须使用 REST 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));