ts-mongoose-pagination
v1.1.2
Published
Typescript pagination plugin for mongoose
Downloads
261
Maintainers
Readme
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:
import { mongoosePagination } from "ts-mongoose-pagination";
const userSchema = new Schema({
username: String,
accounts: [{ type: ObjectId, ref: "Account" }]
});
userSchema.plugin(mongoosePagination);
const User: PaginateModel<TUser> = mongoose.model("User", userSchema);
//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:
interface IPaginateResult<T> {
data: T[];
pagination: IPagination;
}
interface IPagination {
hasPrevPage: boolean;
hasNextPage: boolean;
prevPage: number | null;
nextPage: number | null;
perPage: number;
page?: number | null;
totalPages?: number;
}
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:
yarn
yarn test
Examples
Detailed examples could be found in Pagination.test.ts
Paginate with
await Model.paginate({})
});
More advanced example
var conditions = {};
var options = {
select: "title date author",
sort: { date: -1 },
populate: "account",
lean: true,
perPage: 5
};
User.paginate(conditions, options).then(result => {
// ...
});
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.paginate(conditions, {offset:50, limit: 10}).then(result => { // ...
why not just use:
User.find(conditions, { offset: 50, limit: 10 }).then(result => { // ... });
Acknowledgement
Thanks for the insparation from the following mongoose pagination js implementation. mongoose-paginate mongoose-paginate-v2