从服务器端的mongoose分页

我正在尝试将服务器端分页添加到NodeJS,Express和MongoDB API。

API使用mongoose来处理数据库。

我迷失在如何自定义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); 

所有客户的控制器:

 const mongoose = require("mongoose"); const Client = require('../models/client'); const clientController = {}; clientController.index = (limit, callback) => { Client.find(callback).limit(limit); }; module.exports = clientController; 

获得客户的路线:

  app.get('/api/clients', (req, res) => { Client.index(limit,(err, client) => { if (err) { res.status(500).json({ msg: "Error en aplicacion", err }); } res.status(200).json(client); }); }); 

我如何在控制器中自定义结果如下所示:

 [ { "totalRecords":"99999999999", "offset":"888888", "page":"4", "nextPage":"5" "result":{...} } ] 

我已经有一个函数来计算分页,但是我不知道如何在控制器的结果中添加关于分页的信息。

在路由中添加分页数据之前,我想处理控制器中的分页逻辑。

或者更好地处理路线中的分页?

提前致谢

您可以在称为paginate的mongoose模型中创build一个方法:

在声明mongoose模型之前添加这个:

 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); 

然后在控制器更改:

 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); }); 

});