【发布时间】:2019-10-08 06:21:37
【问题描述】:
我正在尝试显示其他用户发送给用户的最新消息。
如果,
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
}
});
编辑:
我试过这个:
await Conversation.aggregate(
[
// Matching pipeline, similar to find
{
$match: {
recipient: id
}
},
// Sorting pipeline
{
$sort: {
date: -1
}
},
// Grouping pipeline
{
$group: {
_id: "$sender",
text: {
$first: "$text"
},
date: {
$first: "$date"
}
}
},
// Project pipeline, similar to select
{
$project: {
_id: 0,
sender: "$_id"
text: 1
}
}
],
function(err, messages) {
// Result is an array of documents
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
console.log("latestMessages", messages);
return res.json(messages);
}
}
)
来自here 的回答,但它返回一个空数组 + 它似乎不会填充sender
【问题讨论】:
标签: javascript node.js mongodb mongoose