Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Mongodb Mongoose sort and paginate chat messages

I am making a chat app where 10 messages are loaded per page. The messages are sorted from oldest to latest, so the new messages come in bottom and old messages are in top. I tried to use skip() and limit() methods it didnt work.

let count = page*10

MessageModel.find(find_query).sort({createdAt: 'asc'}).skip(count-10).limit(10).exec();

for example:

let these be my messages sorted oldest to newest: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

the above query returns the data like this in 1st page: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

2nd page : ["11", "12"]

but I want it to return

in 1st page: ["3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

in 2nd page: ["1", "2"]

EDIT: I tried sorting it into descending and reversing, this seemed to fix the issue.

let count = page*10

const messages = await MessageModel.find(find_query).sort({createdAt: 'desc'}).skip(count-10).limit(10).exec();

const re_messages = messages.reverse()

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Since you want to display messages 3 to 12 first, you need to sort using 'desc' instead of 'asc', so as to get the newest messages first. This will give you ["12", "11", ... "4", "3"]. Now all you have to do is to invert this array to get ["3", "4", ... "11", "12"]:

let count = page*10

let messages = await MessageModel
                        .find(find_query)
                        .sort({createdAt: 'desc'}) // get the latest ones
                        .skip(count-10)
                        .limit(10)
                        .exec()
                        .lean(); // Get a simple array

messages.reverse(); // ["3", "4", ... "11", "12"]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!