Reputation: 46441
I have Label
, Conversations
and Messages
models...
Label contains Conversations id's... I have used $lookup which works for conversation
const conversation = await Label.aggregate([
{ $match: { _id: mongoose.Types.ObjectId("5abcb74bb59afe4310c60266") } },
{ $lookup: {
from: 'conversations',
localField: 'conversations',
foreignField: '_id',
as: "conversations"
}
}])
and gives output like
[{
_id: 5abcb74bb59afe4310c60266,
name: 'Archive',
value: 'archive',
user: 5abc93a85d3914318cc8d3d7,
conversations: [ [Object], [Object] ],
__v: 0
}]
Now I have messages
inside conversations
[{
_id: 5abe07717a978c41b270b1bc,
messages: [ 5abe07717a978c41b270b1bd ],
members: [ 5abc93a85d3914318cc8d3d7, 5abc9467b7c99332f0a6813c ],
__v: 0
}]
So how do I apply $lookup for the messages fields which is inside
label -> conversations -> messasges
Thanks in advance
Upvotes: 0
Views: 463
Reputation: 511
You will have to use $unwind
on $conversations
. This will cause your conversations
array to explode and you will now have as much documents as conversations in your hands.
Then you should do your $lookup
, and (if wanted) $group
to fallback on what you had before $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'
}
}
])
Upvotes: 1