If you want to retrieve the 12 users with the most clicks, you'd use this query:
firebase.database()
.ref("reachers_by_user_id")
.orderByChild("click")
.limitToLast(12)
.once("value")
.then(snapshot => {
snapshot.forEach(snap => {
console.log(snap.key+": "+snap.val().click);
});
});
If you run this code you'll see it prints (up to) the 12 highest click counts, in ascending order. This is because Firebase Realtime Database queries always sort nodes in ascending order. There is no way to get the result in descending order. For more on this, see:
In your case, you can easily reverse the (up to) 12 results in the callback with:
.then(snapshot => {
let results = [];
snapshot.forEach(snap => {
results.push(snap);
});
results = results.reverse();
});
To get to the next twelve, or actually the previous 12, you will need to use endAt
passing in:
- The
click
value of the lowest value you already got.
- The key of that snapshot, which is used to disambiguate in case there are multiple child nodes with the same
click
value.
So you'd get the top 12 scores with:
var lowestClickValue, lowestKey;
firebase.database()
.ref("reachers_by_user_id")
.orderByChild("click")
.limitToLast(12)
.once("value")
.then(snapshot => {
var isFirst = true;
snapshot.forEach(snap => {
console.log(snap.key+": "+snap.val().click);
if (isFirst) {
lowestKey = snap.key
lowestClickValue = snap.val().click
isFirst = false;
}
});
});
After running this code, the lowestClickValue
and lowestKey
variables hold the click
and key for the lowest node on the current page. You then get the next page with:
firebase.database()
.ref("reachers_by_user_id")
.orderByChild("click")
.endAt(lowestClickValue, lowestKey)
.limitToLast(13)
Here we request 13 nodes, since there will be one node we already have. You'll need to exclude that node in your client-side code.
Note that pagination in Firebase is non-trivial, but quite consistent once you understand that the API is not based on offsets. I highly recommend studying some of the other questions on the pagination if you are still having problems.