【发布时间】:2021-04-21 07:45:47
【问题描述】:
我正在为我的应用构建一个简单的聊天功能。我在发送和接收消息时遇到了一点问题。
这是我的消息架构:
const MessageSchema = new mongoose.Schema({
from: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
to: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
text: {
type: String,
required: true
},
seen: {
type: Boolean,
default: false
},
createdAt: {
type: Date,
required: true
}
});
假设我有这个消息文件:
[
{
from: "5fef2536ad845e385c34a22f", // My Own ID
to: "5fef2575ad845e385c34a232" // Example user "John",
text: "I sent this"
...
},
{
from: "5fffdc903eaf522cb8d20994", // Example user "Dave"
to: "5fef2536ad845e385c34a22f" // My Own ID,
text: "Dave sent this"
...
}
]
这是我对发送和接收消息的看法
await Message.aggregate([
{
$match: {
$or: [ { from: req.user._id },{ to: req.user._id }]
}
},
{ $sort: { createdAt: -1 } },
{
$group: {
_id: '$to',
from: { $first: '$from' },
text: { $first: '$text' }
...
}
},
{
$project: {
_id: 0,
to: '$_id',
from: 1,
text: 1
}
}
])
上述聚合产生:
[
// This is the message I sent
{
from: "5fef2536ad845e385c34a22f",
to: "5fef2575ad845e385c34a232",
text: "I sent this"
...
}
...
// I CAN'T FETCH RECEIVED MESSAGES
]
我能够得到最后一个我发送的消息,因为我只将它们与to 分组在一起,我只发送了哪些消息。我想不出一种方法如何通过分别分组来同时获取已发送和已接收的消息。
我应该改变我为我的消息建模的方式吗?如果您能帮助我,我将不胜感激。
【问题讨论】:
标签: mongodb mongoose aggregation-framework