Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A page based custom aggregate pagination library for Mongoose with customizable labels.

License

NotificationsYou must be signed in to change notification settings

aravindnc/mongoose-aggregate-paginate-v2

Repository files navigation

Banner

mongoose-aggregate-paginate-v2

npm versionBuild Statuscontributions welcomeDownloadsGitHub commit activitynpms.ionpms.io

A page based custom aggregate pagination library forMongoose with customizable labels.

If you are looking for basic query pagination library without aggregate, use this onemongoose-paginate-v2

Installation

npm install mongoose-aggregate-paginate-v2

Usage

Adding the plugin to a schema,

varmongoose=require("mongoose");varaggregatePaginate=require("mongoose-aggregate-paginate-v2");varmySchema=newmongoose.Schema({/* your schema definition */});mySchema.plugin(aggregatePaginate);varmyModel=mongoose.model("SampleModel",mySchema);

and then use modelaggregatePaginate method,

// as PromisevarmyModel=require("/models/samplemodel");constoptions={page:1,limit:10,};varmyAggregate=myModel.aggregate();myModel.aggregatePaginate(myAggregate,options).then(function(results){console.log(results);}).catch(function(err){console.log(err);});
// as CallbackvarmyModel=require('/models/samplemodel');constoptions={page:1,limit:10};varmyAggregate=myModel.aggregate();myModel.aggregatePaginate(myAggregate,options,function(err,results){if(err){console.err(err);else{console.log(results);}})
// Execute pagination from aggregateconstmyModel=require('/models/samplemodel');constoptions={page:1,limit:10};constmyAggregate=myModel.aggregate();myAggregate.paginateExec(options,function(err,results){if(err){console.err(err);else{console.log(results);}})

Model.aggregatePaginate([aggregateQuery], [options], [callback])

Returns promise

Parameters

  • [aggregate-query] {Object} - Aggregate Query criteria.Documentation
  • [options] {Object}
    • [sort] {Object | String} - Sort order.Documentation
    • [offset=0] {Number} - Useoffset orpage to set skip position
    • [page] {Number} - Current Page (Defaut: 1)
    • [limit] {Number} - Docs. per page (Default: 10).
    • [customLabels] {Object} - Developers can provide custom labels for manipulating the response data.
    • [pagination] {Boolean} - Ifpagination is set to false, it will return all docs without adding limit condition. (Default: True)
    • [allowDiskUse] {Bool} - To enable diskUse for bigger queries. (Default: False)
    • [countQuery] {Object} - Aggregate Query used to count the resultant documents. Can be used for bigger queries. (Default:aggregate-query)
    • [useFacet] {Bool} - To use facet operator instead of using two queries. This is the new default. (Default: true)
  • [callback(err, result)] - (Optional) 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:

  • docs {Array} - Array of documents
  • totalDocs {Number} - Total number of documents that match a query
  • limit {Number} - Limit that was used
  • page {Number} - Current page number
  • totalPages {Number} - Total number of pages.
  • offset {Number} - Only if specified or defaultpage/offset values were used
  • hasPrevPage {Bool} - Availability of prev page.
  • hasNextPage {Bool} - Availability of next page.
  • prevPage {Number} - Previous page number if available or NULL
  • nextPage {Number} - Next page number if available or NULL
  • pagingCounter {Number} - The starting sl. number of first document.
  • meta {Object} - Object of pagination meta data (Default false).

Please note that the above properties can be renamed by setting customLabels attribute.

Sample Usage

Return first 10 documents from 100

constoptions={page:1,limit:10,};// Define your aggregate.varaggregate=Model.aggregate();Model.aggregatePaginate(aggregate,options).then(function(result){// result.docs// result.totalDocs = 100// result.limit = 10// result.page = 1// result.totalPages = 10// result.hasNextPage = true// result.nextPage = 2// result.hasPrevPage = false// result.prevPage = null}).catch(function(err){console.log(err);});

With custom return labels

Now developers can specify the return field names if they want. Below are the list of attributes whose name can be changed.

  • totalDocs
  • docs
  • limit
  • page
  • nextPage
  • prevPage
  • totalPages
  • hasNextPage
  • hasPrevPage
  • pagingCounter
  • meta

You should pass the names of the properties you wish to changes usingcustomLabels object in options. Labels are optional, you can pass the labels of what ever keys are you changing, others will use the default labels.

If you want to return paginate properties as a separate object then definecustomLabels.meta.

Same query with custom labels

constmyCustomLabels={totalDocs:'itemCount',docs:'itemsList',limit:'perPage',page:'currentPage',nextPage:'next',prevPage:'prev',totalPages:'pageCount',hasPrevPage:'hasPrev',hasNextPage:'hasNext',pagingCounter:'pageCounter',meta:'paginator'};constoptions={page:1,limit:10,customLabels:myCustomLabels};// Define your aggregate.varaggregate=Model.aggregate();Model.aggregatePaginate(aggregate,options,function(err,result){if(!err){// result.itemsList [here docs become itemsList]// result.itemCount = 100 [here totalDocs becomes itemCount]// result.perPage = 10 [here limit becomes perPage]// result.currentPage = 1 [here page becomes currentPage]// result.pageCount = 10 [here totalPages becomes pageCount]// result.next = 2 [here nextPage becomes next]// result.prev = null [here prevPage becomes prev]// result.hasNextPage = true [not changeable]// result.hasPrevPage = false [not changeable]}else{console.log(err);};

Usingoffset andlimit

Model.aggregatePaginate(aggregate,{offset:30,limit:10},function(err,result){// result});

UsingcountQuery

// Define your aggregate query.varaggregate=Model.aggregate();// Define the count aggregate query. Can be different from `aggregate`varcountAggregate=Model.aggregate();// Set the count aggregate queryconstoptions={countQuery:countAggregate,};Model.aggregatePaginate(aggregate,options).then(function(result){// result}).catch(function(err){console.log(err);});

Usingprepagination

This allows you to paginate the result at a given placeholder stage in a pipeline rather than at the end which is the default behavior. This can be useful when you have a large dataset and you want to paginate before carrying out expensive operations such as$lookup or$unwind.

// Define your pipelineconstpipeline=[{$match:{status:"active",},},{$sort:{date:-1,},},"__PREPAGINATE__",{$lookup:{from:"authors",localField:"author",foreignField:"_id",as:"author",},},];Model.aggregatePaginate(pipeline,options).then(function(result){// result}).catch(function(err){console.log(err);});

Global Options

If you want to set the pagination options globally across the model. Then you can do like below,

letmongooseAggregatePaginate=require("mongoose-aggregate-paginate-v2");letBookSchema=newmongoose.Schema({title:String,date:Date,author:{type:mongoose.Schema.ObjectId,ref:"Author",},});BookSchema.plugin(mongooseAggregatePaginate);letBook=mongoose.model("Book",BookSchema);// Like this.Book.aggregatePaginate.options={limit:20,};

Release Note

Moved to CHANGELOG.md

License

MIT

About

A page based custom aggregate pagination library for Mongoose with customizable labels.

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors11


[8]ページ先頭

©2009-2025 Movatter.jp