1

How can I get let's say the oldest 5 records from MongoDB using mongoose and after let's say the next 5 records and so on. What I have by now is this

Model.find().sort({time: -1}).limit(5).exec( ...);

But I want after some time to get next 5, how can I do this?

iBug
  • 35,554
  • 7
  • 89
  • 134
S. Georgian
  • 143
  • 1
  • 2
  • 11
  • Please don't insert excessive dots into your post. It will only earn you downvotes for bad look. – iBug Feb 15 '18 at 14:52
  • Don't know specifically about mongoose & nodejs, but if you want to process 5 records at a time, I would look at mongo cursor. Instead of limiting search by `limit(5)`, I would fetch 5 records from the cursor, process them, fetch the next 5 and so on. You can also, use `skip` keyword, which tells Mongo to skip certain number of records. But this requires running the query every time, which is inefficient. – Ajay M Feb 15 '18 at 14:56
  • Possible duplicate of https://stackoverflow.com/questions/5539955/how-to-paginate-with-mongoose-in-node-js – chridam Feb 15 '18 at 15:11

1 Answers1

3

Based on request number update page. eg. first request send page=0, for next page=1 and so on.

var limit = 5;
var page = 0; // 1,2,3,4

return Model.find()
        .sort({time: -1})
        .limit(limit)
        .skip(limit * page)
        .exec();
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37