Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make pagination with mongoose

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?

like image 526
Erik Avatar asked Sep 22 '12 09:09

Erik


People also ask

What is pagination in mongoose?

mongoose-paginate-v2 is a pagination library having a page wrapper. The main usage of the plugin is you can alter the return value keys directly in the query itself so that you don't need any extra code for transformation.

How does pagination work in MongoDB?

In MongoDB, the pagination phenomenon is used to get an output that can be easily understandable. Pagination is a procedure to display large disarranged output in a page format. With the help of pagination, the result can be retrieved faster as compared to the general methods of MongoDB.

What is skip and limit in mongoose?

The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.


1 Answers

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 
});
like image 86
Yosvel Quintero Arguelles Avatar answered Sep 22 '22 18:09

Yosvel Quintero Arguelles