Mongoose pagination from server side

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)){
        if(err){
            totalCount = 0;
        }
        else{
            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){

        if(err){
            return callback('Error Occured', null);
        }
        else if(!docs){
            return callback('Docs Not Found', null);
        }
        else{
            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) => {
    //You could put page number in request query ro request params
    Client.paginate(req.body.pageNo, function(err, response) {
        if (err) {
            return res.status(500).json({
                message : "Error en aplicacion",
                error : err
            });
        }
        return res.status(200).json(response);
    });
});