我正在尝试显示其他用户发送给用户的最新消息。因此,如果,User A sends Message 1 to User B,User A sends Message 2 to User B,User B sends Message 3 to User A,User A sends Message 4 to User B,User C sends Message 5 to User B如果我是用户 B,查看我的收件箱,只将用户 A 的消息 4 返回给用户 B,将用户 C 的消息 5 返回给用户 B。我怎样才能做到这一点?到目前为止我已经尝试过这个: const messages = await Conversation.find({ recipient: id }) .sort({ date: -1 }) .distinct("sender") .populate("sender")但是 a) 它没有填充sender,它返回messages [ 5d9b5142d6606f12f5434d41 ]b) 我不确定这是正确的查询。我的型号:const conversationSchema = new Schema({ sender: { type: mongoose.Schema.Types.ObjectId, ref: "user" }, senderHandle: { type: String, required: true }, recipient: { type: mongoose.Schema.Types.ObjectId, ref: "user" }, text: { type: String, required: true }, unread: { type: Boolean, default: true }, date: { type: Date, default: Date.now }});
2 回答
潇潇雨雨
TA贡献1833条经验 获得超4个赞
更改您的匹配管道
$match: {
recipient: mongoose.Types.ObjectId(id);
}
在管道末尾添加这些
{
$lookup: {
from: "users",
localField: "sender",
foreignField: "_id",
as: "sender"
}
}
{ "$unwind": { path: "$sender" } }
慕神8447489
TA贡献1780条经验 获得超1个赞
istinct 返回一个 id 数组而不是对象数组,因此,它没有属性,您无法填充它。
由于您想获取最新消息,我建议您使用 findOne 而不是 find。
const message = await Conversation.findOne({recipient: id}, {}, {
sort: { 'date' : -1 } })
.populate('sender');
添加回答
举报
0/150
提交
取消
