Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

430
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda