0

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?

user3174311
  • 1,714
  • 5
  • 28
  • 66
  • In the `next` it should be: `_id: {$gt: picture.id}` – nimrod serok May 29 '22 at 14:37
  • AH, you are correct, sorry for the stupid copy and paste. – user3174311 May 29 '22 at 14:40
  • So I guess this solves it – nimrod serok May 29 '22 at 15:15
  • It would be useful if there was a `created_date` field for each document, in such situations. Also see: [How does MongoDB order their docs in one collection?](https://stackoverflow.com/questions/33018048/how-does-mongodb-order-their-docs-in-one-collection). – prasad_ May 30 '22 at 02:18
  • That's very interesting, so using The id is not so reliable. I actually have a created date field on that collection, I'll update the code to use it. Thank you for the hint. – user3174311 May 30 '22 at 06:52

0 Answers0