DbTheChain
DbTheChain

Reputation: 235

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&page=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)
    .sort({'date' : 1})
    .skip(pagesize*(page-1))
    .limit(pagesize)
    .exec(function(err, result) {
      if (err) return next(err);
      res.json({
        confirmation: 'success',
        result: result
      })
    });
})

Upvotes: 1

Views: 807

Answers (1)

robertklep
robertklep

Reputation: 203231

You're using all query string parameters as properties to query:

var params = req.query;

Because you're now adding a new query string parameter page, this will affect your query. In your URL example, the query becomes this:

{
  isActive : 'true',
  page     : '16'
}

You should remove that parameter before using req.query as a query document:

var page = req.query.page;
delete req.query.page;

var params = req.query;

Upvotes: 1

Related Questions