Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

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"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading