Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase results range using startAt and endAt

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?

like image 336
Tom Maton Avatar asked Jan 26 '16 22:01

Tom Maton


1 Answers

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.

like image 87
Frank van Puffelen Avatar answered Oct 19 '22 16:10

Frank van Puffelen