简体   繁体   中英

cursor pagination mongodb mongoose

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 })

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM