mongoose-find-and-paginate
v0.2.3
Published
A Mongoose plugin for a pagination
Downloads
11
Readme
mongoose-find-and-paginate
A Mongoose plugin that provides a method, findAndPaginate(), for performing a find and a calculation pagination parameters at the same time.
Install
npm install mongoose-find-and-paginate --save
API
findAndPaginate
Parameters
filter
Object The filteroptions
Object The Mongoose.Query options. Used for pagination:options.page
number The page number (optional).options.perPage
number The number of documents on page (optional).options.skip
number The number of documents to skip (optional). Used only if thepage
is not set.options.offset
number Alias forskip
(optional). Used only if thepage
is not set.options.limit
number Maximum number of documents (optional). Used only if thepage
is not set.
callback
Function
Returns Mongoose.Query<QueryResult>
QueryResult
Type: Object
Properties
docs
Array<Mongoose.Document> The Array of documentstotalDocs
number Total number of documents that match a querytotalPages
number Total number of pages
Usage
Add plugin
import mongoose from 'mongoose';
import findAndPaginatePlugin from 'mongoose-find-and-paginate';
const schema = new mongoose.Schema({ ... });
schema.plugin(findAndPaginatePlugin);
const Model = mongoose.model('Model', schema);
Use skip(offset) & limit
const filter = { ... };
const { docs, totalDocs } = await Model.findAndPaginate(filter, {
skip: 10,
limit: 5,
sort: '_id'
});
Use page & perPage
const filter = { ... };
const { docs, totalPages } = await Model.findAndPaginate(filter, {
page: 3,
perPage: 5,
sort: '_id'
});
Use with Mongoose.Query methods
const filter = { ... };
const query = Model
.findAndPaginate(filter, { page: 3, perPage: 5 })
.populate(...)
.select(...);
const { docs, totalPages } = await query.exec();