Home > front end >  How do I know if there are more documents left to get from a firestore collection?
How do I know if there are more documents left to get from a firestore collection?

Time:03-02

I'm using flutter and firebase. I use pagination, max 5 documents per page. How do I know if there are more documents left to get from a firestore collection. I want to use this information to enable/disable a next page button presented to the user.

limit: 5 (5 documents each time)

orderBy: "date" (newest first)

startAfterDocument: latestDocument (just a variable that holds the latest document)

This is how I fetch the documents.

collection.limit(5).orderBy("date", descending: true).startAfterDocument(latestDocument).get()

I thought about checking if the number of docs received from firestore is equal to 5, then assume there are more docs to get. But this will not work if I there are a total of n * 5 docs in the collection.

I thought about getting the last document in the collection and store this and compare this to every doc in the batches I get, if there is a match then I know I've reach the end, but this means one excess read.

Or maybe I could keep on getting docs until I get an empty list and assume I've reached the end of the collection.

I still feel there are a much better solution to this.

Let me know if you need more info, this is my first question on this account.

CodePudding user response:

There is no flag in the response to indicate there are more documents. The common solution is to request one more document than you need/display, and then use the presence of that last document as an indicator that there are more documents.

This is also what the database would have to do to include such a flag in its response, which is probably why this isn't an explicit option in the SDK.

You might also want to check the documentation on keeping a distributed count of the number of documents in a collection as that's another way to determine whether you need to enable the UI to load a next page.

  • Related