---
title: "monoose实现翻页"
author: "start_p"
date: "2014-10-17T13:11:17Z"
tags: []
categories: ["编程语言"]
slug: "monoose"
draft: false
lastmod: "2014-10-17T13:11:17Z"
id: 2144651
url: "https://guard.iteye.com/blog/2144651"
---

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

首先看下mongoose API，find方法源码：

01. `Model.find = function find (conditions, fields, options, callback) {`
02. `if ('function' == typeof conditions) {`
03. `callback = conditions;`
04. `conditions = {};`
05. `fields = null;`
06. `options = null;`
07. `} else if ('function' == typeof fields) {`
08. `callback = fields;`
09. `fields = null;`
10. `options = null;`
11. `} else if ('function' == typeof options) {`
12. `callback = options;`
13. `options = null;`
14. `}`
15. `// get the raw mongodb collection object`
16. `var mq = new Query({}, options, this, this.collection);`
17. `mq.select(fields);`
18. `if (this.schema.discriminatorMapping && mq._selectedInclusively()) {`
19. `mq.select(this.schema.options.discriminatorKey);`
20. `}`
21. `return mq.find(conditions, callback);`
22. `};`

 

 

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

/\**  
 * huopanpan  
 \*/

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,查询所有字段，第三个参数有倒序，分页。  
然后就是页面上两个翻页按钮：

/\**  
 * huopanpan  
 \*/

&lt;ul class="pager"&gt;  
    &lt;li&gt;&lt;a href="/admin/blogList?pageIndex=&lt;%= pageIndex==1?1:parseInt(pageIndex)-1%&gt;&pageSize=5"&gt;← Older&lt;/a&gt;&lt;/li&gt;  
    &lt;li&gt;&lt;a href="/admin/blogList?pageIndex=&lt;%= pageCount&lt;5?pageIndex:parseInt(pageIndex)+1%&gt;&pageSize=5"&gt;Newer →&lt;%= pageCount%&gt;&lt;/a&gt;&lt;/li&gt;  
&lt;/ul&gt;);