0
votes

Firestore has this guide on how to paginate a query:

Firestore - Paginate data with query cursors

They show the following example:

Paginate a query

Paginate queries by combining query cursors with the limit() method. For example, use the last document in a batch as the start of a cursor for the next batch.

var first = db.collection("cities")
       .orderBy("population")
       .limit(25);

return first.get().then(function (documentSnapshots) {
 // Get the last visible document
 var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
 console.log("last", lastVisible);

 // Construct a new query starting at this document,
 // get the next 25 cities.
 var next = db.collection("cities")
         .orderBy("population")
         .startAfter(lastVisible)
         .limit(25);
});

QUESTION

I get the example, but how can I know how many items (in total, without the limit restriction) that query will return? I'll need that to calculate the number of pages and control the pagination component, won't I?

I can't simply display next and back buttons without knowing the limit.

How is it supposed to be done? Am I missing something?

2

2 Answers

1
votes

You can't know the size of the result set in advance. You have to page through all the results to get the total size. This is similar to not being able to know the size of a collection without also recording that yourself somewhere else - it's just not scalable to provide this information, in the way that Cloud Firestore needs to scale.

1
votes

this is not possible, the iterator cannot know how many documents it contains, as they are fetched via a gRPC stream.

But there is a workaround... but you have to make a few stuff:

1) write a counter in a firebase doc, which you increment or decrement everything you make a transaction

2) store the count in a field of your new entry, like position 10 or something.

Then you create an index on that field (position DESC).

This way you can do a skip+limit with a where("position", "<", N).orderBy("position", DESC)

It's complex but it does the trick