Gathering detailed insights and metrics for mongoose-paginate-v2
Gathering detailed insights and metrics for mongoose-paginate-v2
Gathering detailed insights and metrics for mongoose-paginate-v2
Gathering detailed insights and metrics for mongoose-paginate-v2
A custom pagination library for Mongoose with customizable labels.
npm install mongoose-paginate-v2
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
503 Stars
315 Commits
91 Forks
3 Watching
7 Branches
32 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-5.7%
22,986
Compared to previous day
Last week
-0.3%
131,961
Compared to previous week
Last month
4.4%
555,201
Compared to previous month
Last year
54%
5,090,254
Compared to previous year
31
A custom pagination library for Mongoose with customizable labels.
If you are looking for aggregate query pagination, use this one mongoose-aggregate-paginate-v2
mongoose-paginate-v2 is a pagination library having a page wrapper. The main usage of the plugin is you can alter the return value keys directly in the query itself so that you don't need any extra code for transformation. The initial idea of this plugin is loosely based on mongoose-paginate package by github.com/edwardhotchkiss/. So this can be considered as an upgraded version of mongoose-paginate with much more options.
The below documentation is not perfect. Feel free to contribute. :)
1npm install mongoose-paginate-v2
Add plugin to a schema and then use model paginate
method:
1const mongoose = require('mongoose'); 2const mongoosePaginate = require('mongoose-paginate-v2'); 3 4const mySchema = new mongoose.Schema({ 5 /* your schema definition */ 6}); 7 8mySchema.plugin(mongoosePaginate); 9 10const myModel = mongoose.model('SampleModel', mySchema); 11 12myModel.paginate().then({}); // Usage
Prior to version 1.5.0
, types need to be installed from DefinitelyTyped.
To declare a PaginateModel
in your Typescript files:
1import mongoose from 'mongoose'; 2import paginate from 'mongoose-paginate-v2'; 3 4// declare your schema 5export const institutionSchema = new mongoose.Schema({ name: String }); 6 7// paginate with this plugin 8institutionSchema.plugin(paginate); 9 10// declare a mongoose document based on a Typescript interface representing your schema 11interface InstitutionDocument extends mongoose.Document, InstitutionData {} 12 13// create the paginated model 14const model = mongoose.model< 15 InstitutionDocument, 16 mongoose.PaginateModel<InstitutionDocument> 17>('Institutions', institutionSchema, 'institutions');
Returns promise
Parameters
[query]
{Object} - Query criteria. Documentation
[options]
{Object}
[select]
{Object | String} - Fields to return (by default returns all fields). Documentation[collation]
{Object} - Specify the collation Documentation[sort]
{Object | String} - Sort order. Documentation[populate]
{Array | Object | String} - Paths which should be populated with other documents. Documentation[projection]
{String | Object} - Get/set the query projection. Documentation[lean=false]
{Boolean} - Should return plain javascript objects instead of Mongoose documents? Documentation[leanWithId=true]
{Boolean} - If lean
and leanWithId
are true
, adds id
field with string representation of _id
to every document[offset=0]
{Number} - Use offset
or page
to set skip position[page=1]
{Number}[limit=10]
{Number}[customLabels]
{Object} - Developers can provide custom labels for manipulating the response data.[pagination]
{Boolean} - If pagination
is set to false, it will return all docs without adding limit condition. (Default: True
)[useEstimatedCount]
{Boolean} - Enable estimatedDocumentCount for larger datasets. Does not count based on given query, so the count will match entire collection size. (Default: False
)[useCustomCountFn]
{Boolean} - Enable custom function for count datasets. (Default: False
)[forceCountFn]
{Boolean} - Set this to true, if you need to support $geo queries. (Default: False
)[customFind]
{String} - Method name for the find method which called from Model object. This options can be used to change default behaviour for pagination in case of different use cases (like mongoose-soft-delete). (Default 'find'
)[allowDiskUse]
{Boolean} - Set this to true, which allows the MongoDB server to use more than 100 MB for query. This option can let you work around QueryExceededMemoryLimitNoDiskUseAllowed errors from the MongoDB server. (Default: False
)[read]
{Object} - Determines the MongoDB nodes from which to read. Below are the available options.
[pref]
: One of the listed preference options or aliases.[tags]
: Optional tags for this query. (Must be used with [pref]
)[options]
{Object} - Options passed to Mongoose's find()
function. Documentation[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:
docs
{Array} - Array of documentstotalDocs
{Number} - Total number of documents in collection that match a querylimit
{Number} - Limit that was usedhasPrevPage
{Bool} - Availability of prev page.hasNextPage
{Bool} - Availability of next page.page
{Number} - Current page numbertotalPages
{Number} - Total number of pages.offset
{Number} - Only if specified or default page
/offset
values were usedprevPage
{Number} - Previous page number if available or NULLnextPage
{Number} - Next page number if available or NULLpagingCounter
{Number} - The starting index/serial/chronological number of first document in current page. (Eg: if page=2 and limit=10, then pagingCounter will be 11)meta
{Object} - Object of pagination meta data (Default false).Please note that the above properties can be renamed by setting customLabels attribute.
1const options = { 2 page: 1, 3 limit: 10, 4 collation: { 5 locale: 'en', 6 }, 7}; 8 9Model.paginate({}, options, function (err, result) { 10 // result.docs 11 // result.totalDocs = 100 12 // result.limit = 10 13 // result.page = 1 14 // result.totalPages = 10 15 // result.hasNextPage = true 16 // result.nextPage = 2 17 // result.hasPrevPage = false 18 // result.prevPage = null 19 // result.pagingCounter = 1 20});
Now developers can specify the return field names if they want. Below are the list of attributes whose name can be changed.
You should pass the names of the properties you wish to changes using customLabels
object in options.
Set the property to false to remove it from the result.
Same query with custom labels
1const myCustomLabels = { 2 totalDocs: 'itemCount', 3 docs: 'itemsList', 4 limit: 'perPage', 5 page: 'currentPage', 6 nextPage: 'next', 7 prevPage: 'prev', 8 totalPages: 'pageCount', 9 pagingCounter: 'slNo', 10 meta: 'paginator', 11}; 12 13const options = { 14 page: 1, 15 limit: 10, 16 customLabels: myCustomLabels, 17}; 18 19Model.paginate({}, options, function (err, result) { 20 // result.itemsList [here docs become itemsList] 21 // result.paginator.itemCount = 100 [here totalDocs becomes itemCount] 22 // result.paginator.perPage = 10 [here limit becomes perPage] 23 // result.paginator.currentPage = 1 [here page becomes currentPage] 24 // result.paginator.pageCount = 10 [here totalPages becomes pageCount] 25 // result.paginator.next = 2 [here nextPage becomes next] 26 // result.paginator.prev = null [here prevPage becomes prev] 27 // result.paginator.slNo = 1 [here pagingCounter becomes slNo] 28 // result.paginator.hasNextPage = true 29 // result.paginator.hasPrevPage = false 30});
For conveniently passing on all request query parameters into paginate(), without having to specify them all in the controller, you can use the PaginationParameters-class. The example below is with express.js code, but can be applied to any request, where the query string has been parsed into an object.
1const { PaginationParameters } = require('mongoose-paginate-v2'); 2 3// req.query = { 4// page: 1, 5// limit: 10, 6// query: {"color": "blue", "published": true} 7// projection: {"color": 1} 8// } 9 10req.get('/route', (req, res) => { 11 Model.paginate(...new PaginationParameters(req).get()).then((result) => { 12 // process the paginated result. 13 }); 14 15 console.log(new PaginationParameters(req).get()); // [{ color: "blue", published: true }, { page: 1, limit: 10, projection: { color: 1 } }] 16});
Note: req.query.projection
and req.query.query
have to be valid JSON. The same goes for any option which is passed into Model.paginate() as an array or object.
Using offset
and limit
:
1Model.paginate({}, { offset: 30, limit: 10 }, function (err, result) { 2 // result.docs 3 // result.totalPages 4 // result.limit - 10 5 // result.offset - 30 6});
With promise:
1Model.paginate({}, { offset: 30, limit: 10 }).then(function (result) { 2 // ... 3});
1var query = {}; 2var options = { 3 select: 'title date author', 4 sort: { date: -1 }, 5 populate: 'author', 6 lean: true, 7 offset: 20, 8 limit: 10, 9}; 10 11Book.paginate(query, options).then(function (result) { 12 // ... 13});
You can use limit=0
to get only metadata:
1Model.paginate({}, { limit: 0 }).then(function (result) { 2 // result.docs - empty array 3 // result.totalDocs 4 // result.limit - 0 5});
config.js:
1var mongoosePaginate = require('mongoose-paginate-v2'); 2 3mongoosePaginate.paginate.options = { 4 lean: true, 5 limit: 20, 6};
controller.js:
1Model.paginate().then(function (result) { 2 // result.docs - array of plain javascript objects 3 // result.limit - 20 4});
If you need to fetch all the documents in the collection without applying a limit. Then set pagination
as false,
1const options = { 2 pagination: false, 3}; 4 5Model.paginate({}, options, function (err, result) { 6 // result.docs 7 // result.totalDocs = 100 8 // result.limit = 100 9 // result.page = 1 10 // result.totalPages = 1 11 // result.hasNextPage = false 12 // result.nextPage = null 13 // result.hasPrevPage = false 14 // result.prevPage = null 15 // result.pagingCounter = 1 16});
If you need to use your own custom count function, then set useCustomCountFn
as your custom count function. Make sure the function is returning count as a promise.
1const options = { 2 useCustomCountFn: function () { 3 return Promise.resolve(100); 4 }, 5}; 6 7Model.paginate({}, options, function (err, result) { 8 // result.docs 9});
Determines the MongoDB nodes from which to read.
1const options = { 2 lean: true, 3 limit: 10, 4 page: 1, 5 read: { 6 pref: 'secondary', 7 tags: [ 8 { 9 region: 'South', 10 }, 11 ], 12 }, 13}; 14 15Model.paginate({}, options, function (err, result) { 16 // Result 17});
If you want to paginate your sub-documents, here is the method you can use.
1var query = { name: 'John' }; 2var option = { 3 select: 'name follower', 4 pagingOptions: { 5 // your populate option 6 populate: { 7 path: 'follower', 8 }, 9 page: 2, 10 limit: 10, 11 }, 12}; 13 14// Only one document (which object key with name John) will be return 15const result = await Book.paginateSubDocs(query, option);
Sets the allowDiskUse option, which allows the MongoDB server to use more than 100 MB for query. This option can let you work around QueryExceededMemoryLimitNoDiskUseAllowed
errors from the MongoDB server.
Note that this option requires MongoDB server >= 4.4. Setting this option is a no-op for MongoDB 4.2 and earlier.
1const options = { 2 limit: 10, 3 page: 1, 4 allowDiskUse: true, 5}; 6 7Model.paginate({}, options, function (err, result) { 8 // Result 9});
Below are some references to understand more about preferences,
There are few operators that this plugin does not support natively, below are the list and suggested replacements.
But we have added another option. So if you need to use $near and $nearSphere please set forceCountFn
as true and try running the query.
1const options = { 2 lean: true, 3 limit: 10, 4 page: 1, 5 forceCountFn: true, 6}; 7 8Model.paginate({}, options, function (err, result) { 9 // Result 10});
$geoNear, $near, and $nearSphere may not work (Untested). This will be updated in the future plugin versions.
npm run test
. In order to run the tests, you need to have the Mongo Deamon running locally.npm run lint && npm run prettier
to lint and format every relevant fileNo vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
2 existing vulnerabilities detected
Details
Reason
6 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 5
Reason
security policy file detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
Found 4/27 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Moremongoose-aggregate-paginate-v2
A cursor based custom aggregate pagination library for Mongoose with customizable labels.
@types/mongoose-aggregate-paginate-v2
TypeScript definitions for mongoose-aggregate-paginate-v2
mongoose-paginate
Pagination plugin for Mongoose
@octokit/plugin-paginate-rest
Octokit plugin to paginate REST API endpoint responses