javascript - Mongoskin 中的分页(跳过 + 限制)

标签 javascript node.js mongodb mongoskin

通过查看 mongodb 示例,我尝试了一些操作,例如:

// returns an empty array
funnyPosts.find({limit:5}).toArray(function(err, result) {
    console.log(result);
});

也试过

// returns { _construct_args: [],

console.log(db.collection('funny_posts').find().skip(3).limit(3));

最佳答案

您是否正在尝试使用 Node.js 和 MongoDB 实现分页?

您的参数位置错误(不是 find() 的第一个参数)。这是我的 HackHall 代码 GitHub link :

exports.getPosts = function(req, res, next) {
  var limit = req.query.limit || LIMIT;
  var skip = req.query.skip || SKIP;
  req.db.Post.find({}, null, {
    limit: limit,
    skip: skip,
    sort: {
      '_id': -1
    }
  }, function(err, obj) {
    if (!obj) next('There are not posts.');
    obj.forEach(function(item, i, list) {
      if (req.session.user.admin) {
        item.admin = true;
      } else {
        item.admin = false;
      }
      if (item.author.id == req.session.userId) {
        item.own = true;
      } else {
        item.own = false;
      }
      if (item.likes && item.likes.indexOf(req.session.userId) > -1) {
        item.like = true;
      } else {
        item.like = false;
      }
      if (item.watches && item.watches.indexOf(req.session.userId) > -1) {
        item.watch = true;
      } else {
        item.watch = false;
      }
    });
    var body = {};
    body.limit = limit;
    body.skip = skip;
    body.posts = obj;
    req.db.Post.count({}, function(err, total) {
      if (err) next(err);
      body.total = total;
      res.json(200, body);
    });
  });
};

有关更多信息,请查看我在 webapplog.com 上的其他帖子和 Express.js Guide .

关于javascript - Mongoskin 中的分页(跳过 + 限制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22364858/

相关文章:

javascript - 如果网站位于框架/iframe 内,document.referer 是否始终包含值?

javascript - JQuery 循环隐藏项目

javascript - 通过 javascript/jQuery 访问嵌套 JSON 对象时出现问题

javascript - 如何检查 node-orm 中的列是否有 NULL 值

javascript - 无法使用带有express的mongodb调用未定义的方法 'get'

Javascript - 依赖于其他对象的对象

node.js - fs.createWriteStream 错误 :ENOENT

javascript - 如何正确捕获 promise 中的错误?

python - 将 db.collection.drop() 中的 'collection' 解释为变量与设置数据库

mongodb - 带有 MongoDB 的 MapReduce 真的非常慢(30 小时,而同等数据库在 MySQL 中为 20 分钟)