6

I'm trying to get the first 100 results from my Firebase data, then the next 100, then the next 100 etc. I've tried multiple ways.

Version 1

ref.child('products').orderByChild('domain').startAt(0).endAt(100).once('value').then(function(snapshot) {});

Version 2

ref.child('products').orderByChild('domain').startAt(0).limitToFirst(100).once('value').then(function(snapshot) {});

Version 3

ref.child('products').startAt(0).endAt(100).once('value').then(function(snapshot) {});

Every time the snapshot returned is null. Is there anyway in Firebase of getting the range of data I'm after?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Tom Maton
  • 1,564
  • 3
  • 23
  • 41

1 Answers1

10

When you call orderByChild() any subsequent call to startAt(), endAt() or equalTo() expects the value that you pass in to be a child. You're passing in an index. Unless the value of domain is a sequential index (highly unlikely), this will not work.

What you should do is remember the domain value of the last child you got, and then pass that in to startAt() for the next "page".

var productsRef = ref.child('products');
var lastKnownDomainValue = null;
var pageQuery = productsRef.orderByChild('domain').limitToFirst(100);
pageQuery.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    lastKnownDomainValue = childSnapshot.child('domain').val();
  });
});

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

var nextQuery = productsRef.orderByChild('domain').startAt(lastKnownDomainValue).limitToFirst(100);

And then you update lastKnownDomainValue when you loop over the children again.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Couldn't you collapse `pageQuery` and `nextQuery` into a single function that could accept any range? – Clay Banks Dec 17 '16 at 06:07
  • @frank-van-puffelen Are you saying Firebase doesn't support range queries where you have a start value (say a date) and and end value? and if so, does Firestore also have that limitation? – Aodh Mar 09 '18 at 14:57
  • 1
    @Aodh Range queries with a start and end value are possible on both. If you're having trouble, post a question with the minimal code that reproduces where you are stuck. – Frank van Puffelen Mar 09 '18 at 15:15