How to paginate with Mongoose in Node.js? How to paginate with Mongoose in Node.js? mongoose mongoose

How to paginate with Mongoose in Node.js?


I'm am very disappointed by the accepted answers in this question. This will not scale. If you read the fine print on cursor.skip( ):

The cursor.skip() method is often expensive because it requires the server to walk from the beginning of the collection or index to get the offset or skip position before beginning to return result. As offset (e.g. pageNumber above) increases, cursor.skip() will become slower and more CPU intensive. With larger collections, cursor.skip() may become IO bound.

To achieve pagination in a scaleable way combine a limit( ) along with at least one filter criterion, a createdOn date suits many purposes.

MyModel.find( { createdOn: { $lte: request.createdOnBefore } } ).limit( 10 ).sort( '-createdOn' )


After taking a closer look at the Mongoose API with the information provided by Rodolphe, I figured out this solution:

MyModel.find(query, fields, { skip: 10, limit: 5 }, function(err, results) { ... });


Pagination using mongoose, express and jade - Here's a link to my blog with more detail

var perPage = 10  , page = Math.max(0, req.params.page)Event.find()    .select('name')    .limit(perPage)    .skip(perPage * page)    .sort({        name: 'asc'    })    .exec(function(err, events) {        Event.count().exec(function(err, count) {            res.render('events', {                events: events,                page: page,                pages: count / perPage            })        })    })


matomo