mongoose pagination from server side

mongoose pagination from server side

I am trying to add server side pagination to a NodeJS, Express and MongoDB API.
The API use mongoose to handle the database.
I am lost in how to customize the response from the Controller.
const mongoose = require(‘mongoose’);
const Schema = mongoose.Schema;

const clientSchema = Schema({
code: {
type: String,
required: [true,’Code no puede estar vacio’]
name: {
type: String,
required: [true,’Name no puede estar vacio’]
timestamps: true

const Client = module.exports = mongoose.model(‘clients’,clientSchema);

Controller for get all clients:
const mongoose = require(“mongoose”);
const Client = require(‘../models/client’);
const clientController = {};

clientController.index = (limit, callback) => {

module.exports = clientController;

Route to get the clients:
app.get(‘/api/clients’, (req, res) => {
Client.index(limit,(err, client) => {

if (err) {
msg: “Error en aplicacion”,

How can I customize the result in the controller to something like this:

I already have a function to calculate the pagination, But I don’t know how to add the information about the pagination in the result of the controller.
Before I was adding the pagination data in the route, But I want to handle the pagination logic in the controller.
Or is better handle the pagination in the route?
Thanks in advance


Solution 1:

You can create a method in mongoose model called as paginate :

Add this before declaring mongoose model :

clientSchema.methods.paginate = function(pageNo, callback){

    var limit = 10;
    var skip = pageNo * (limit - 1);
    var totalCount;

    //count documents
    this.count({}, function(err, count)){
            totalCount = 0;
            totalCount = count;
    if(totalCount == 0){
        return callback('No Document in Database..', null);
    //get paginated documents
    this.find().skip(skip).limit(limit).exec(function(err, docs){

            return callback('Error Occured', null);
        else if(!docs){
            return callback('Docs Not Found', null);
            var result = {
                "totalRecords" : totalCount,
                "page": pageNo,
                "nextPage": pageNo + 1,
                "result": docs
            return callback(null, result);



const Client = module.exports = mongoose.model('clients',clientSchema);

Then in controller change :

app.get('/api/clients', (req, res) => {
  Client.paginate(pageNo, function(err, response){

    if (err) {
      return res.status(500).json({
        message : "Error en aplicacion",
        error : err
    return res.status(200).json(response);