pfinferno
pfinferno

Reputation: 1945

mongoose .find with pagination returning 0 elements

I'm trying to get pagination working properly, but for some reason, mongoose is returning zero items.

Here's the relevant code in nodejs:

if (req.query.name) {
  match.name = req.query.name;
}


// initial pageSize is 2
// initial page is 1
pageSize = parseInt(req.query.pagesize);
page = parseInt(req.query.page);
const foods = await Food.find({ match })
  .skip(pageSize * (page - 1))
  .limit(pageSize);
res.send({
  foods,
});

Now, I've used this same technique using .populate with a different route and have gotten the result I'm looking for like so:

await req.user
.populate({
    path: 'pets',
    options: {
      limit: req.query.pagesize,
      skip: req.query.pagesize * (req.query.page - 1),
    },
  })
  .execPopulate();

I can't figure out what's wrong. There's 20 items in the database. If I remove the .limit and .skip and just have the .find, I retrieve all the items.

Upvotes: 0

Views: 142

Answers (1)

DutchKevv
DutchKevv

Reputation: 199

It seems like you are pasting in the wrong value to .find()

Shouldn't you place .find({name: req.query.name}) or .find(match) in your case??

Now it says ({match: {name: req.query.name}}) wich doesn't work I believe

Upvotes: 3

Related Questions