Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

331
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda