I used the reference of mongoose-paginate library and this library has some node version-related issues. Because of it, I rewrited all code using "async, await", optimize code, and changed parameters.
Pagination plugin for Mongoose
npm install mongoose-paginate-async-await
Add plugin to a schema and then use model paginate
method:
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate-async-await');
var schema = new mongoose.Schema({ /* schema definition */ });
schema.plugin(mongoosePaginate);
var Model = mongoose.model('Model', schema); // Model.paginate()
Parameters
[query]
{Object} - Query criteria. Documentation[options]
{Object}[select]
{Object | String} - Fields to return (by default returns all fields). Documentation[sort]
{Object | String} - Sort order. Documentation[populate]
{Array | Object | String} - Paths which should be populated with other documents. Documentation[lean=false]
{Boolean} - Should return plain javascript objects instead of Mongoose documents? Documentation[page=1]
{Number}[perPage=10]
{Number}
[callback(err, result)]
- If specified the callback is called once pagination results are retrieved or when an error has occurred
Return value
Promise fulfilled with object having properties:
data
{Array} - Array of documentsdocuments
{Number} - Total number of documents in collection that match a queryselect
{Object | String} - Selected fieldssort
{Object | String} - Selected fieldspage
{Number} - Page values were usedpages
{Number} - Pages values were usedperPage
{Number} - PerPage that was used
With async/await:
const result = await Model.paginate({}, { page: 3, perPage: 10 });
With callback function:
Model.paginate({}, { page: 3, perPage: 10 }, function(err, result) {});
With promise:
Model.paginate({}, { page: 3, perPage: 10 }).then(function(result) {});
var query = {};
var options = {
select: 'title date author',
sort: { date: -1 },
populate: 'author',
lean: true,
page: 1,
perPage: 10
};
const result = await Model.paginate({}, { page: 3, perPage: 10 });
config.js:
var mongoosePaginate = require('mongoose-paginate');
mongoosePaginate.paginate.options = {
lean: true,
perPage: 20
};