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?