javascript - 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 },
});
解决方案
在这里,我假设您想获取某个用户(比如用户 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
]);
推荐阅读
- java - Shuffling images
- python - How can I convert a pandas column of time to different columns of hours and minutes?
- arrays - How to save a subdocument array in an existing schema whose data is coming from a dynamic form?
- python - Creating a table in Python without using Pandas
- python - add one more new column supplytypecheck, check if supply type IMPG that should be Y else N
- wordpress - Facing issue to get updated result by using "TI Wishlist" wordpress plugin API in IONIC
- kotlin - kotlin 中泛型类型表示法之间的区别
- wordpress - How to create repository for WordPress site in GitLab?
- three.js - Rotation of Y axis (on Marker Based AR) only goes up to 90 degrees
- java - What is an efficient method to cancel multiple AsyncTask callbacks that will return in the future if a condition is met midway?