Firebase result range using startAt and endAt

I am trying to get the first 100 results from my Firebase data, then the next 100, then the next 100, etc. I tried several 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) {}); 

Each time a snapshot is returned, null. Anyway, in Firebase, to get the range of data I need?

+4
source share
1 answer

When calling orderByChild() any subsequent call to startAt() , endAt() or equalTo() expects the value you pass to be a child. You pass the index. If the domain value is a sequential index (highly unlikely), this will not work.

What you need to do is remember the domain value for your last child, and then pass this 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 the lastKnownDomainValue variable, which has the last domain you have ever seen. To get the following batch of children, you pass this value to startAt() :

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

And then you update lastKnownDomainValue when you loop back on them again.

+6
source

Source: https://habr.com/ru/post/1011598/


All Articles