Giter Club home page Giter Club logo

express-mongoose-pagination's Introduction

Introduction


Hello Folks,

Pagination of data is highly recommended if you want to fetch large number of records from the collection. For eg: All users from Users collection. If you fetch the records without pagination, it may result in slow performance at both back-end and front-end side.

So, this tool will help you to paginate your data without impacting the performance.

You need to use this tool with find() query method of mongoose ODM to make it work.

You just need to pass the request object, and some optional parameters to the paginate() method of this tool, it will return an object with useful information that you can use to handle you data with ease.

I have explained it's implementation below:


Installation


Install with the following command

npm i express-mongoose-pagination or npm install express-mongoose-pagination


Implementation


1. Import the module in model

//UserModel.js

const pagination = require('express-mongoose-pagination')

or

//ES6+
import pagination from 'express-mongoose-pagination'

2. Apply as plugin to your Schema Instance

//UserModel.js

const userSchema = new Schema({...})

userSchema.plugin(pagination)

module.exports = mongoose.model('User', userSchema)

or

//ES6+
export default mongoose.model('User', userSchema)

3. Somewhere inside your routes block

//routes.js
const User = require('../models/UserModel.js')

or

import User from '../models/UserModel.js'

//Users route get request
app.get('/users', async function(req, res){

   //1. Use the find query method normally without any restrictions. You can pass all available parameters like condition, projection, options, etc

   const users = await User.find().paginate(req, { withQueryString: true })

   res.render('views/users.html', { users }) //render and pass users

})

That's It


Data Object and Query Parameters


You will get the output data in the form of object as mentioned below:


//console.log(users)

{
   currentPage: 1// Current page number,
   data: [
      {_id:1, name:'User 1', email: '[email protected]'},
      {...},
      {...},
      .
      .
      .
      //upto 15 records

   ] // Array of data objects,
   firstPageUrl: 'https://xyz.com/users?page=1',
   lastPageUrl: 'https://xyz.com/users?page=4',
   lastPage: 4 // Last page number,
   nextPageUrl: 'https://xyz.com/users?page=2',
   prevPageUrl: null,
   path: 'https://xyz.com/users',
   perPage: 15 //Per page value,
   total: 60 //Total matched records in users collection
}

//If there is no records you will get same object format with changed values and most of them will be null or empty array for data field.

Pre-defined parameters:

Parameter Usage Default Value Is Required Data Type
page Navigation between pages 1 No Int/Number
perPage Number of Records per page 15 No Int/Number

Custom parameters:

You can pass n number of query parameters with your endpoint and that will reflect in all url specific fields except path field.

Note: By default custom query string option is disabled, you can enable it by passing withQueryString as a boolean value

//pass withQueryString option like this

const users = await User.find({ sortIndex: {$gt: 10 } })
                .sort({ sortIndex: 1 })
                .paginate(request, { withQueryString:true })

// Output will be like this
{
   currentPage:1,
   .
   .
   firstPageUrl: 'https://xyz.com/users?page=1&perPage=10&foo=bar&john=doe',
   lastPageUrl: 'https://xyz.com/users?page=4&perPage=10&foo=bar&john=doe',
   .
   .

}                

Serial Numbers:

You can pass _sno as boolean to options parameters object to paginate function to get data with serial numbers.

//pass _sno option like this

const users = await User.find({ sortIndex: {$gt: 10 } })
                .sort({ sortIndex: 1 })
                .paginate(request, { withQueryString:true, _sno:true })

// Output will be like this
{
   currentPage:1,
   data:[
      {
         ...
         ...
         _sno: 1
      },
      {
         ...
         ...
         _sno: 2
      }
      ....
   ]
   .
   firstPageUrl: 'https://xyz.com/users?page=1&perPage=10&foo=bar&john=doe',
   lastPageUrl: 'https://xyz.com/users?page=4&perPage=10&foo=bar&john=doe',
   .
   .

}                

License


MIT


Show your Support


If you like my work, please support and share it to your fellow people.


Thank you and have a great time ahead!

express-mongoose-pagination's People

Contributors

gocodecraving avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.