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

427
Visualizações
Mongoose .sort breaks .skip & .limit

So i've implemented infiniscroll with mongoose and my query looks like this

const posts = await Seed.find({status: 'APPROVED', 'color.name': color})
  .skip(parseInt(skip) || 0)
  .limit(8)
  .exec()

That works great, from 0 to the end of posts. However if i add .sort({upvotes: -1})

const posts = await Seed.find({status: 'APPROVED', 'color.name': color})
  .sort({upvotes: -1})
  .skip(parseInt(skip) || 0)
  .limit(8)
  .exec()

Everything goes nuts, i can get the same post 6 times.

I've stared at this for hours now and i simply cannot understand why this is happening and it feels like a bug.

I've tried .sort('-upvotes'), .sort({upvotes: 'desc'}), .sort({'upvotes': 'desc'})

Update: Sorting by .sort('-date') actually works, so i'm having a problem with upvotes specifically. The majority of posts has 1 upvote. Does mongoose randomize then? Sounds really strange if it did

If anyone can help me figure this out i would be very thankful

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Basically your question is similar to pagination.

Because your multiple documents contain same value of upvotes, mongo does not able to recognise the difference(between same values) and can give same document over and over.

For example your suppose your limit is 2 and following are your documents.

[{
  upvotes: 1,
  doc: "a"
}, {
  upvotes: 2,
  doc: "b"
}, {
  upvotes: 2,
  doc: "c"
}, {
  upvotes: 3,
  doc: "d"
}]

Now if you use sort with upvotes: -1 and limit 2

You might get at first page

[{
  upvotes: 3,
  doc: "d"
}, {
  upvotes: 2,  // here mongo fails to make difference
  doc: "c"     // document c
}]

or can give

[{
  upvotes: 3,
  doc: "d"
}, {
  upvotes: 2,  // here mongo fails to make difference
  doc: "b"     // document b
}]

Means mongo randomly throws the documents having same sort field value.

Solution is too simple here just put _id accordingly

const posts = await Seed.find({ status: 'APPROVED', 'color.name': color})
  .sort({upvotes: -1, _id: -1 })
  .skip(parseInt(skip) || 0)
  .limit(8)
  .exec()
over 4 years ago · Santiago Trujillo Relatório
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