ts-mongoose-pagination
Typescript pagination plugin for Mongoose
Installation
npm install ts-mongoose-pagination
or
yarn add ts-mongoose-pagination
Usage
Add plugin for a mongoose schema to inject a paginate
method for pagination:
; ;userSchema.pluginmongoosePagination;; //User.paginate()
Model.paginate([query conditions], [options], [callback])
Parameters
[query]
{Object} - Query conditions. Documentation[options]
{Object}[select]
{Object | String} - Fields to return (by default returns all fields). Documentation[sort]
{Object | String} - Sort order. Documentation[populate]
{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}, if undefined, will return all docs without pagination[perPage=10]
{Number}, number of docs per page, default is 10
[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 an IPaginateResult:
Tests
Coverage
--------------|----------|----------|----------|----------|-------------------|File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | --------------|----------|----------|----------|----------|-------------------|All files | 96.43 | 70 | 80 | 96.43 | | src | 97.73 | 75 | 100 | 97.73 | | index.ts | 97.73 | 75 | 100 | 97.73 | 116 |--------------|----------|----------|----------|----------|-------------------|
Run tests
- Set up local mongo db
- Run:
yarnyarn test
Examples
Detailed examples could be found in Pagination.test.ts
Paginate with
await Model.paginate});
More advanced example
;; User.paginateconditions, options.then;
Explaination for some choices made
-
Why remove the offset in the options? Think about the scenario when we use offset and limit(refer to the implementation in mongoose-paginate)
User.paginateconditions, .thenwhy not just use:
User.findconditions, .then;
Acknowledgement
Thanks for the insparation from the following mongoose pagination js implementation. mongoose-paginate mongoose-paginate-v2