使用mongoose 添加分页方法,暂时还没发现什么更好的方法,我使用的方法是,直接在源码中添加
找到 node_modules/mongoose/lib/model.js打开这个文件,里面添加这段代码
/** * author:gtt * updateTime:2014-5-3 */ Model.execPageQuery = function find (currentPage,pageSize, conditions, fields, options, callback) { if (‘function‘ == typeof conditions) { callback = conditions; conditions = {}; fields = null; options = null; } else if (‘function‘ == typeof fields) { callback = fields; fields = null; options = null; } else if (‘function‘ == typeof options) { callback = options; options = null; } //var countLine = 20;// 总行数 //var countPage = (countLine + pageSize-1 )/pageSize;// 总页数 var StartLine = (currentPage -1)*pageSize; var m = this; async.parallel([ function(cb) { m.count({},cb); }, function(cb) { if (‘function‘ == typeof conditions) { m.find({}).limit(pageSize).skip(StartLine).exec(cb); } else if (‘function‘ == typeof fields) { m.find(conditions).limit(pageSize).skip(StartLine).exec(cb); } else if (‘function‘ == typeof options) { m.find(conditions,fields).limit(pageSize).skip(StartLine).exec(cb); }else{ m.find(conditions,fields,options).limit(pageSize).skip(StartLine).exec(cb); } } ], function(err,rs){ var page = {};//总页数 总条数 集合 if(‘number‘ == typeof rs[0]){ page.total = rs[0]; page.rows = rs[1]; }else{ page.total = rs[1]; page.rows = rs[2]; } callback(err,page); }); }调用方法:
var assert = require(‘assert‘) var util=require(‘util‘); var mongoose = require(‘mongoose‘); var Schema = mongoose.Schema; var ObjectId = mongoose.Types.ObjectId; mongoose.connect(‘mongodb://localhost:8888/test‘); mongoose.connection.on(‘error‘, function() { console.error(‘connection error‘, arguments); }); var PersonSchema = new Schema({ name : String }); var Person = mongoose.model(‘Person‘, PersonSchema,‘Person‘); Person.execPageQuery(1,100,function(err,rel){ console.dir(rel); });
成天都在实现这种烂玩意,啥时候自己也搞一套牛逼的。
mongoose 数据库操作 - 分页,布布扣,bubuko.com
原文:http://blog.csdn.net/pro_tian/article/details/24895513