5

Firebase has some very basic query functionality with orderBy*, limitTo*, startAt(), etc. Is there a way to tell Firebase you want the 10th result of a request? For example, I am using orderByKey(). Since the keys are these awesome magical strings, you cannot use integers to reference any position within them. I would like store a pointer to a location in keys and move through it. I want to orderByKey(), and arbitrarily get key N. Is this possible?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Maitreya
  • 1,237
  • 11
  • 13

2 Answers2

10

While you cannot access child items by index with Firebase, you can store the key of an item and use that to start a next query.

var ref = new Firebase('https://yours.firebaseio.com/items');
var lastKnownKey = null;
var firstQuery = ref.orderByKey().limitToFirst(100);
firstQuery.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    lastKnownKey = childSnapshot.key();
  });
});

Now you have a variable lastKnownKey that has the last key you've ever seen. To get the next batch of children, you pass that value in to startAt():

var nextQuery = ref.orderByKey().startAt(lastKnownKey).limitToFirst(100);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
3

Note that in conjunction with @frank-van-puffelen 's answer, you can also use the shallow argument to the top-level query.

I don't know how this is translated to the JavaScript firebase API, but with curl, this would be something like:

curl 'https://your-site.firebaseio.com/questions.json?shallow=true'

which returns something like:

{
  "-Ju2tGTo6htY2e4mbuPO": true,
  "-Ju3AWjZnhnUw_OfGyk4": true,
  "-JughjjzbFOxjevE2ykY": true,
  "-Jw3cciI6ZpoK1ejfK58": true,
  "-Jw4NhcgJ9DnenBVphyq": true,
  "-JwE5ojQ5ZjkvTzVK9E2": true,
  "-JwE7Qbpf9r1YN8Qaoss": true,
  "-JwFIQ3pGMCI0E3xzPIz": true,
}

Then, once you've gotten your shallow list of items, you can query them one at a time in any order you want by accessing the key directly:

curl 'https://your-site.firebaseio.com/questions/-Ju2tGTo6htY2e4mbuPO.json'
pbanka
  • 716
  • 1
  • 8
  • 20
  • Yup. Great addition. You can indeed address specific messages directly this way, or use the keys from the shallow JSON in the `startAt()` call. – Frank van Puffelen Jan 29 '16 at 19:40