我的模式:
export const MessagesAllSchema = new Schema({
senderName: {type: String, required: true},
senderId: {type: String, required: true},
content: String,
date: {type: Date, default: Date.now()},
roomId: Schema.Types.ObjectId,
});我的问题是:
AllMessages.find(
{roomId: [roomId1, roomId2]},
(err, messages) => {
console.log(messages);
},
).sort({date: -1});我的代码返回
我的代码返回来自1号房间和2号房间的几条信息。
我想要实现
我希望我的代码返回1房间的一条消息和2房间的一条消息。如果我应用.limi(2),我得到了1房间的2条消息,但我希望每个房间得到一条消息。
发布于 2020-10-22 10:17:35
使用find()是不可能的,您可以尝试合计()方法,
$match roomId在roomIds阵列中的应用$group通过roomId获得第一条消息从root变量中的多个分组消息中获得$replceWith替换根对象$sort$limit 2文档const messages = await AllMessages.aggregate([
{
$match: {
roomId: { $in: [roomId1, roomId2] }
}
},
{
$group: {
_id: "$roomId",
root: { $first: "$$ROOT" }
}
},
{ $replaceWith: "$root" },
{ $sort: { date: -1 } },
{ $limit: 2 }
]).exec();
console.log(messages);https://stackoverflow.com/questions/64479461
复制相似问题