How to make pagination with mongoose


Question

I want to make a pagination feature in my Collection. How can find a documents with 'start' and 'limit' positions and get total document number in a single query?

1
10
9/22/2012 9:34:25 AM

Accepted Answer

You can't get both results in one query; the best you can do is to get them both using one Mongoose Query object:

var query = MyModel.find({});
query.count(function(err, count) {...});
query.skip(5).limit(10).exec('find', function(err, items) {...});

Use a flow control framework like async to cleanly execute them in parallel if needed.

18
10/13/2013 4:59:51 PM

You can use the plugin Mongoose Paginate:

$ npm install mongoose-paginate

After in your routes or controller, just add :

Model.paginate({}, { page: 3, limit: 10 }, function(err, result) {
    // result.docs 
    // result.total 
    // result.limit - 10 
    // result.page - 3 
    // result.pages 
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon