我有Label
,Conversations
和Messages
型号......
标签包含对话ID' s我使用了$ lookup,用于对话
const conversation = await Label.aggregate([
{ $match: { _id: mongoose.Types.ObjectId("5abcb74bb59afe4310c60266") } },
{ $lookup: {
from: 'conversations',
localField: 'conversations',
foreignField: '_id',
as: "conversations"
}
}])
并输出
之类的输出[{
_id: 5abcb74bb59afe4310c60266,
name: 'Archive',
value: 'archive',
user: 5abc93a85d3914318cc8d3d7,
conversations: [ [Object], [Object] ],
__v: 0
}]
现在我messages
内有conversations
[{
_id: 5abe07717a978c41b270b1bc,
messages: [ 5abe07717a978c41b270b1bd ],
members: [ 5abc93a85d3914318cc8d3d7, 5abc9467b7c99332f0a6813c ],
__v: 0
}]
那么如何对
中的消息字段应用$ lookup标签 - >对话 - > messasges
提前致谢
答案 0 :(得分:1)
您必须在$unwind
上使用$conversations
。这会导致您的conversations
数组爆炸,现在您手中的对话文件数量会很多。
然后你应该执行$lookup
和(如果需要的话)$group
来回溯$unwind
之前的内容
const conversation = await Label.aggregate([
{ $match: { _id: mongoose.Types.ObjectId("5abcb74bb59afe4310c60266") } },
{ $lookup: {
from: 'conversations',
localField: 'conversations',
foreignField: '_id',
as: "conversations"
}
},
{ $unwind: "$conversations" },
{
$lookup: {
from: 'messages',
localField: 'conversations.messages',
foreignField: '_id',
as: 'myMessages'
}
}
])