0

I'm using pagination to reduce the number of calls with Firestore, I managed to set it up correctly.

But I also need to get the total number of all the documents upfront corresponding to the query which looks something like this:

let query = db.collection("Posts").document(uid).collection("Posts").order(by: "timestamp", descending: true)

If I need to get the total number of documents upfront what's the point in paginating? Is there a point to it?

To be clear I only need the number of documents and not to read them all at the beginning.

StackGU
  • 868
  • 9
  • 22

2 Answers2

1

Firestore does not make it possible to get a document count without executing a query. Any counts or other aggregations that you require will need to be computed as a running tally and stored elsewhere, perhaps in another document, requiring at least a single read of that document.

See also:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

More to your point: you generally do NOT need to know the total # of documents to page through the documents. Just keep paging forwards until the query returns fewer documents than your specified page size - which means you've reached the end.

I have libraries that page both forward and backward through a query - in my case, sorted alphabetically - so it's obvious from the displayed data approximately where the paging is in the collection. I'm sure your data-sorted collection is similar. It's not the count users care about - it's approximately how close to the end they are.

This is a basic "feature" of NoSQL, and rather than fighting it and complaining, design your UI so that it isn't an issue.

LeadDreamer
  • 3,303
  • 2
  • 15
  • 18
  • I understand completely what you're saying, and I agree with you, my issue started when I wanted to paginate a series of images like on an instagram page. at the top of the page is written the total number of images the user has uploaded, so it must be that there's no pagination. – StackGU Jan 05 '21 at 10:41
  • 1
    or, as mentioned elsewhere, they maintain a count AS THE IMAGES ARE SAVED, for display later, rather than counting at the time of display. It's your code. Don't let them save images without counting them. – LeadDreamer Jan 05 '21 at 17:00