7

I'm trying to trying to do pagination with an optional filter option with Mongoose.

I have it working with the pagination by making 2 queries to the database, one to get a count of the documents and one to actually get the data. Without pagination, my filters work properly as well. I was wondering is there a good way to return from the database both the count of the documents as well as a page (the subset that will be display for the current page) of the data? How could I setup the query to do this?

Currently I'm making two separate calls:

Model.find(filter, selectPaths, {limit: limit, skip: skip}, callback);
Model.count(filter, another_callback);

Do I simply have to make two calls to get all the data I need?

Bryan Cheng
  • 138
  • 1
  • 7

1 Answers1

6

I'll take the liberty and link to my other answers: ranged pagination and pagination with mongodb and node.js.

Short answer: don't use skip/limit, unless your datasets are small (like < 1000 documents or so). The greater page you fetch, the worse it will perform. Use range queries (field: {$gt: value}), they are much more efficient (if indexed, of course).

And no, you can't return total count and part of the data with one query.

Community
  • 1
  • 1
Sergio Tulentsev
  • 210,238
  • 40
  • 347
  • 343
  • How efficient is the use of skip and limit for pagination? For how much data,skip will work without problem? I have read blog posts that says to use range based pagination for large data sets but how much is large datasets? – shrawan_lakhe Feb 25 '16 at 12:09
  • 1
    Did you follow the links in the answer? There's even a number in this very post. – Sergio Tulentsev Feb 25 '16 at 12:29