ITeye博客

monoose实现翻页

start_p · 2014-10-17 13:11 · 编程语言 · Markdown

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

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

  1. Model.find = function find (conditions, fields, options, callback) {
  2. if ('function' == typeof conditions) {
  3. callback = conditions;
  4. conditions = {};
  5. fields = null;
  6. options = null;
  7. } else if ('function' == typeof fields) {
  8. callback = fields;
  9. 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
 */

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。