首页 > 解决方案 > Mongoose,从每次对话中获取最新消息

问题描述

如何从每次对话中获取最新消息

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 },
});

标签: javascriptnode.jsmongoose

解决方案


在这里,我假设您想获取某个用户(比如用户 John)的最新消息。首先,我建议您在聊天对象中添加一个进一步的字段,假设chatId在一对用户之间总是相同的,比如 John -> Anna,反之亦然。这样,跟踪消息会容易得多。

约翰的对象 ID:johnId,聊天 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
            ]);

推荐阅读