Andrew Rasmussen
Andrew Rasmussen

Reputation: 15109

Mongoose: how to implement pagination?

I can't find anything about this. Obviously to fetch a next page you'll want to use .skip and .limit, but how do I find out if there IS a next page? Basically computing has_next_page (boolean).

In raw mongo you can do cursor.hasNext() to see if there's another page.

I can only think of two ways to do it with mongoose:

  1. .limit(pageSize + 1)

    Then return only pageSize results, but use that last one to determine if there's another result or not.

  2. .count()

    Fetch a count for the query and see if it's greater than pageNum * pageSize.

The first seems hacky and second looks very inefficient (counts are expensive, right?), is there no better way to do this?

Upvotes: 2

Views: 1081

Answers (1)

Bassem Reda Zohdy
Bassem Reda Zohdy

Reputation: 12942

Your 1st solution is OK if you don't want to show number of pages but you need to get the count if you want to get number of pages numberOfPages = count/numberPerPage so you will run count() at least once at beginning so you query "or more if you want to be update with this information while user use paged data {I'll ignore this for simplicity if it is critical for you please comment here and lets discuss it}".

so the first query will take sometime here a link about issue on MongoDB about count performance telling that they make improvements for this method https://jira.mongodb.org/browse/SERVER-1752 .

Upvotes: 2

Related Questions