1.0.8 • Published 5 years ago
mongoose-paginate-async-await v1.0.8
mongoose-paginate-async-await
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
Installation
npm install mongoose-paginate-async-awaitUsage
Add mongoosePaginate 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()await Model.paginate(query, options)
OR
Model.paginate(query, options, callback)
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
Examples
Skip 20 documents and return 10 documents
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) {});More advanced example
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 });Set custom default options for all queries
config.js:
var mongoosePaginate = require('mongoose-paginate');
mongoosePaginate.paginate.options = {
lean: true,
perPage: 20
};