Sorting Infinite Scroll with Mongo and Mongoose shows wrong results

381 views
Skip to first unread message

CJ Carter

unread,
Oct 22, 2018, 11:52:31 AM10/22/18
to Mongoose Node.JS ODM
I'm trying to sort the results of my infinite scroll. Basically Mongo pulls 10 docs and I sort those results, then when the user gets tot he bottom is does that again skipping the first 10.

The trouble is, this isn't in order. If I want the data sorted by date. It currentl brings back the top 10 results and sorts that by date AFTER finding based on 'natural order'.

How can I make Mongo find based on date?

*Please keep in mind index and sort() both sort after.

Joe Wagner

unread,
Oct 22, 2018, 12:06:12 PM10/22/18
to Mongoose Node.JS ODM
Hey CJ,

can you post the relevant code? Assuming you're doing a query, and not an aggregation, you need to do something like
 
Model.find({}).sort({date: -1}).skip(10).limit(10).exec(function (err, documents) { ... });

hope that helps

CJ Carter

unread,
Oct 22, 2018, 12:32:16 PM10/22/18
to Mongoose Node.JS ODM
More detials here but find method below: https://stackoverflow.com/questions/52922390/sorting-infinite-scroll-with-mongo-and-mongoose?noredirect=1#comment92772526_52922390

Find:
events = await Event.find({
$and: [
{
active: true
}
]
})
.sort("-time")
.skip(skip)
.limit(limit);

CJ Carter

unread,
Oct 22, 2018, 12:34:27 PM10/22/18
to Mongoose Node.JS ODM
Does the callback allow me to define how mongo performs the find? If find results come back unsorted it's already too late.
SQL does this using OrderBy but it seems Mongo has no orderby ability, It just pulls records to natural order only and allows you to alter docs from there.


On Monday, October 22, 2018 at 9:06:12 AM UTC-7, Joe Wagner wrote:

Joe Wagner

unread,
Oct 22, 2018, 1:57:57 PM10/22/18
to Mongoose Node.JS ODM
I don't think callback vs. await would matter, but can you try it?
Reply all
Reply to author
Forward
0 new messages