使用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);
});
成天都在实现这样的烂玩意,啥时候自己也搞一套牛逼的。