MongoDb Pagination is a library to handle pagination data using MongoDb
this module supports and is tested against:
- mongodb 3+ - lastest
- server/client side rendering
- multiple aggregation/join
- multiple fields search value
- multiple filter fields
- pagination / response in datatable format
- able to use any Methods
(POST,GET, etc),
This module is using async function and the query is using query aggregation()
npm install mongodb-paginationbuildPagination: async (
mongoConfig,
payload,
fieldToSearch,
projection,
aggregate) {
......
}-
Is an
Objectand it'srequired.mongoConfigmust contains keysclientand the maincollectionName. This is used to declaremongodb client connectionas injection.example:
const mongoConfig = { client: client.db('databaseName'), collection: 'user' };
-
the availabe parameters for payload and those are optional:
sortByasstring, default =updatedAtsortTypeasnumber|string||asc|1|desc|-1, default =1searchasstring, default =nullpageasnumber, default =1sizeasnumber, default =10filterasarray, Array<Array[[field, value, operator]]>
filteris used to filtering the data comparing to the value from main collection. Use the mongo operator without$.filterandsearchalso can combined.Noted that if there is no User's query, then set it to be
null.If
payload === null, then it will use default belowpayload : { sort: { updatedAt: 1 }, search: null, page: 1, size: 10, filter: [] }
The
payload.searchis used to search(%s%) within the fields of fieldSearch.This module allows us to use POST,GET, etc. So it can be used depending on which one you are comfortable using.
Note: i suggest to use
GETmethod for best practice.example input:
const payload = { sortBy: 'first_name', sortType: 'desc', search: 'my first_name', filter: [[ "email","mrbontor@gmail.com", 'eq']] page: 2, size: 2 };
-
Is an
Arrayand it'soptional.fieldSearchis used tosearchon any string inpayload.searchBecause this module is used to handle data pagination and as datatable in the client's side, there must be an available field(s) that can be found
There will be a shortage if
fieldsearchis notprovided, which is this module will dooncequery withfind().limit(1)first, then the query results will be set to be data default for fieldSearch and projectionThat is used to get all fields on the collection. Please consider to provide fieldSearch and projection, it will also
increasethequery performancebecause we will only dooncequery.ex. meaning: I only want this fields
first_name,last_name,emailto besearchable, then put them like in example below.example:
const fieldSearch = ['first_name', 'last_name', 'email'];
-
Is an
Objectand it'soptional.projectionis used tofilter/hidethe output from parentcollection.Please consider as i mention above to provide this
parameter- if there is no filtering field(s), set it to be `null`. - if there are fields that need to be `hiddden`, then put them to be `readable`.ex. meaning: assumes that there is password field and it shouldn't be in the output query
const projection = { first_name: 1, last_name: 1, email: 1 };
-
Is an
Objectto dojoin/relationshipof thecollections.ex: meaning: the collection user need to provide user's country and the user's city where in collection user have fields like :
user collection
{ "firstName": "mrbontor", "email": "mrbontor@gmail.com", "countryId": "63e3d2f3...", //ObjectID || string "cityId": "63e3d2f3..." //ObjectID || string }then:
const aggregation = [ { collectionName: 'country', uniqueId: 'countryId' }, { collectionName: 'city', uniqueId: 'cityId' } ];
New Feature on v1.1.1 now its able to filter/search data in sub collections.
You only need to add new keys (
subSearchandfieldToSearch) in paramater aggregation, the config will be like:const aggregation = [ { collectionName: 'country', uniqueId: 'countryId', subSearch: 'country name', fieldToSearch: ['name'] // field name country }, { collectionName: 'city', uniqueId: 'cityId', subSearch: 'country name', fieldToSearch: ['name'] // field name city } ];
Note: even though the field
countryIdandcityIdare not provided in the projection, the filtering/search will be also works.New Feature on v1.2.1 now its able to use projection in sub collections. the format value for projection following the mongodb or use an array instead.
Noted: its recommended to use
projectionwhile using sub collection to enhance the perfomance of the queryconst aggregation = [ { collectionName: 'country', uniqueId: 'countryId', subSearch: 'country name', fieldToSearch: ['name'] // field name country projection: {name: 1, city: 1} // or ['name', 'city'] }, ... ]
there is an example in folder example, please check README for more detail.
const mongoPagination = require('mongodb-pagination');
//prepare configuration
const mongoConfig = {
client: client.getDb().db(),
collection: 'user'
};
//setup payload
const payload = { sortBy: 'first_name' };
//setup searchable fields
const fieldSearch = ['first_name', 'last_name', 'email', 'gender', 'countryId', 'status'];
//setup projection
const projection = { first_name: 1, last_name: 1, email: 1, gender: 1, countryId: 1, status: 1 };
//setup aggregation
const aggregation = [
{
collectionName: 'country',
uniqueId: 'countryId'
}
];
//execute
const pagination = await mongoPagination.buildPagination(mongoConfig, payload, fieldSearch, projection, aggregation);
return pagination;{
"sort": { "first_name": "ASC" },
"page": 1,
"size": 10,
"totalRecord": 0,
"totalPage": 0,
"data": [{...}]
}{
"sort": { "updatedAt": "ASC" },
"page": 1,
"size": 10,
"totalRecord": 100,
"totalPage": 10,
"data": [
{
"_id": "63e3d2f35f96e524a35d7e97",
"first_name": "Tobok",
"last_name": "Sitaggang",
"email": "mrbontor@gmail.eu",
"gender": "Male",
"createdAt": "2023-02-08T15:46:22.377Z",
"updatedAt": "2023-02-08T15:46:22.377Z",
"status": true,
"countryId": { "_id": "63e3ab045f96e524a35d7cde", "name": "Indonesia" }
},
...
]
}{
"sort": { "updatedAt": "ASC" },
"page": 1,
"size": 10,
"totalRecord": 100,
"totalPage": 10,
"data": [
{
"_id": "63e3d2f35f96e524a35d7e97",
"first_name": "Tobok",
"last_name": "Sitaggang",
"email": "mrbontor@gmail.eu",
"gender": "Male",
"createdAt": "2023-02-08T15:46:22.377Z",
"updatedAt": "2023-02-08T15:46:22.377Z",
"status": true,
"countryId": {
"_id":"63e3ab045f96e524a35d7cde","name":"Indonesia"
},
"name": "Indonesia"
},
...
]
}- allow to use
projectionwhen join collection(s) - enable to filter using field instead
- enable to use
projectionfor sub collection - enable filter for sub collection
- allow to use
projectionwhen join collection(s) - enable to filter using field instead
- enable to use
projectionfor sub collection - change LICENCSE, my bad.
Noted: i use coverage: true with the unit test, all have been tested and passed, even though the coverage shown
is no.
npm test1. Fork it!
2. Create your feature branch: git checkout -b my-new-feature
3. Commit your changes: git commit -am 'Add some feature'
4. Push to the branch: git push origin my-new-feature
5. Submit a pull request :D
Noted: i use commitizen to handle commit message, and i'm very thankfull cause it make it easir to handle the versioning.
If my work helps you, please consider
