Home > Enterprise >  cursor pagination mongodb mongoose
cursor pagination mongodb mongoose

Time:10-26

Any mongoose and mongo experts out there that can help me out? As the title says I wanna try and implement cursor based pagination. I've seen an old post here about it but I'm trying to see how I can get the second set of posts.

I get this part

const items = db.items.find({}).sort({
   _id: -1
}).limit(2);

const next = items[items.length - 1]._id
res.json({ items, next })

But how do i apply this second part. Am i suppose to create a separate route for this?

const items = db.items.find({
  _id: { $lt: req.query.next }
}).sort({
   _id: -1
}).limit(2);

const next = items[items.length - 1]._id
res.json({ items, next })

CodePudding user response:

You should implement this in 1 route, using skip and limit.

Like so:

const skip = Number(req.query.skip ?? 0);
const limit = Number(req.query.limit ?? 2);
const items = db.items.find({}).sort({
    _id: -1
}).skip(skip).limit(limit);

const next = items[items.length - 1]._id
res.json({ items, next })

Now for the next page you'll want to send a request including these new query params:

https://myapp.com/myroute?skip=2&limit=2

---- EDIT ----.

using the next object id for skipping instead of skip, like so:

const filterQuery = {};
if (req.query.next) {
    filterQuery._id = {$lt: ObjectId(req.query.next)}
}
const items = db.items.find(filterQuery).sort({
    _id: -1
}).limit(2);

const next = items[items.length - 1]._id
res.json({ items, next })

And the call would be:

https://myapp.com/myroute?next={{itemId}}
  • Related