• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

58
Views
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

3 months ago ·

Santiago Trujillo

1 answers
Answer question

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()
3 months ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.