Home > Blockchain >  Mongodb Mongoose sort and paginate chat messages
Mongodb Mongoose sort and paginate chat messages

Time:02-07

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

CodePudding user response:

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"]
  •  Tags:  
  • Related