Firebase results range using startAt and endAt

寵の児 提交于 2019-12-21 17:53:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35025419/firebase-results-range-using-startat-and-endat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!