最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to only retrieve a list of keys from Firebase? - Stack Overflow

programmeradmin4浏览0评论

I have a node in this form:

index
   $categoryId
     $productId

I wish to retrieve primarily a list of the keys of index, thus an object filled with all the available $categoryId in index.

Is there a way to retrieve this list in Firebase? I am assuming that it is more efficient to retrieve a list of keys than a list with all the data from $categoryId.

I understand that an alternative way is to maintain an index list of all the categories, but this requires some more coding (when categories get edited and deleted).

I have a node in this form:

index
   $categoryId
     $productId

I wish to retrieve primarily a list of the keys of index, thus an object filled with all the available $categoryId in index.

Is there a way to retrieve this list in Firebase? I am assuming that it is more efficient to retrieve a list of keys than a list with all the data from $categoryId.

I understand that an alternative way is to maintain an index list of all the categories, but this requires some more coding (when categories get edited and deleted).

Share Improve this question edited Sep 22, 2017 at 18:01 CommunityBot 11 silver badge asked Dec 10, 2015 at 11:00 NoodlioNoodlio 337 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You can use the shallow keys option in the REST API, but indexing is preferred.

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

Unfortunately, there's no solution in the realtime SDKs. But, I would remend structuring your data to avoid having to use the REST API. Try storing an index of $categoryId in your Firebase database. I know this is extra code, but it's usually a one-liner.

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

With this index, you can just do a realtime listen, or a .once() if preferred.

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

评论列表(0)

  1. 暂无评论