mongoose实现翻页

随着吐槽的内容越来越多,单页显示就显得不够文雅了,分页功能是一个完整系统必备的。所以就决定加上这个功能,不过分页实现起来并不容易,找了下前辈们的资料,感觉都很复杂,所以还是实现一个简单翻页好了,就是只有上一页,下一页这样简单的功能。

首先看下mongoose API,find方法源码:

Model.find = function find (conditions, fields, options, callback){
if("function"==typeof conditions){
    callback = conditions;
    conditions ={};
    fields = null;
    options = null;
}elseif("function"==typeof fields){
    callback = fields;
    fields = null;
     options = null;
 }elseif("function"==typeof options){
     callback = options;
     options = null;
 }
 // get the raw mongodb collection object
   var mq =newQuery({}, options,this,this.collection);
   mq.select(fields);
 if(this.schema.discriminatorMapping && mq._selectedInclusively()){
     mq.select(this.schema.options.discriminatorKey);
 }
 return mq.find(conditions, callback);
 };

其中有4个参数,find(条件,需要查询的字段,选项,回调),这样看着太抽象,来一段实际应用的代码:

router.get("/admin/blogList", function(req, res) {  
    var user = req.session.user;  
    var pageIndex = 1;  
    var pageSize = 5;  
    pageIndex = req.query.pageIndex == undefined ? pageIndex  
            : req.query.pageIndex;  
    pageSize = req.query.pageSize == undefined ? pageSize : req.query.pageSize;  
    Blog.find({}, null, {  
        sort : {  
            "_id" : -1  
        },  
        skip : (pageIndex - 1) \* pageSize,  
        limit : pageSize  
    }, function(err, docs) {  
        if (err)  
            res.send(err.message);  
        res.render("admin/bloglist", {  
            blogList : docs,  
            user : user,  
            pageIndex : pageIndex,  
            pageCount : docs.length  
        });  
    });  
});

其中Blog.find({},null,{sort:{"_id":-1}, skip :( pageIndex -1)* pageSize, limit : pageSize },function)
这一段第一个参数为空,意思查询所有,第二个参数null,查询所有字段,第三个参数有倒序,分页。
然后就是页面上两个翻页按钮:

<ul class="pager">  
    <li><a href="/admin/blogList?pageIndex=<%= pageIndex==1?1:parseInt(pageIndex)-1%>&amp;pageSize=5">&larr; Older</a></li>  
    <li><a href="/admin/blogList?pageIndex=<%= pageCount<5?pageIndex:parseInt(pageIndex)+1%>&amp;pageSize=5">Newer &rarr;<%= pageCount%></a></li>  
</ul>);