Dan P.
Dan P.

Reputation: 1775

Pagination in Mongoskin (skip + limit)

From looking at mongodb examples, I tried a few things, such as:

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

Also tried

// returns { _construct_args: [],

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

Upvotes: 1

Views: 1669

Answers (1)

Azat
Azat

Reputation: 3914

Are you trying to implement pagination with Node.js and MongoDB?

Your parameters in the wrong place (not the first param to find()). Here is my code for 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);
    });
  });
};

For more info look up my other posts on webapplog.com and Express.js Guide.

Upvotes: 2

Related Questions