Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

329
Views
How to get previous and next document in mongoose avoiding to go back to the first?

I have a collection of documents and given a specific document, I want to get the previous and next inserted ones. What I am doing is:

const previous = await Picture.findOne({
    _id: {$lt: picture.id},
}).select('title category').sort({_id: -1});

const next = await Picture.findOne({
    _id: {$lt: picture.id},
}).select('title category').sort({_id: 1});

I found this in this discussion How to fetch next and previous item of the current one with Mongoose and it works, pretty much.

However there is a problem: assuming I have a collection on 10 documents, if I query by the 10th, previous will return the 9th, but next will return the first. How can I avoid this behaviour?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!