how to get the latest message from every conversation
const chatSchema = new schema({
from: { type: schema.Types.ObjectId, ref: "userSchema" },
to: { type: schema.Types.ObjectId, ref: "userSchema" },
text: String,
date: { type: Date, default: Date.now },
});
Here, I suppose you want to get the latest messages for a certain user (say User John). Firstly, I will recommend you add a further field in your chat Object, say chatId
that is always the same between a pair of users say John -> Anna and vice-versa. This way it will be a lot easier to track messages.
John's Object Id: johnId, chat Id: chatId
db.collection.aggregate([
{$match: {$or: [{to: johnId}, {from: johnid}]}, // get messages to and fro user
{$sort: {date: -1}}, // sort the messages in desc order
{$group: {_id: "$chatId", doc: "$first"}} // group messages by chatId and get last message
{$replaceRoot: {newRoot: "$doc"}} // replace the last message with root
]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.