Monday 1 May 2017

Mongoose: Limiting Query result in MongoDB for Pagination

I got a collection with 1k documents and I want to paginate them, by limiting it with only 16 docs pr page, then use the skip method. How would I accomplish that with a URL query?

Right now my route looks like this, but doesn't work - I can query: localhost:3000/api/feed?isActive=true, but I cant limit it with localhost:3000/api/feed?isActive=true&limit=16, as I want.

router.get('/feed', function(req, res, next) {
  var params = req.query;
  var page = req.query.page;
  var pagesize = 16

  Feed.find(params)
    .where({status: { $exists: true }})
    .sort({'date' : 1})
    .skip(pagesize*(page-1))
    .limit(pagesize)
    .exec(function(err, result) {
      if (err) return next(err);
      res.json({
        confirmation: 'success',
        result: result
      })
    });
})



via DbTheChain

No comments:

Post a Comment