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?
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.