How to paginate with Mongoose in Node.js?


Question

I am writing a webapp with Node.js and mongoose. How can I paginate the results I get from a .find() call? I would like a functionality comparable to "LIMIT 50,100" in SQL.

1
198
6/26/2015 3:18:54 PM

Accepted Answer

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) { ... });
202
4/4/2011 3:15:29 PM

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' )

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