How to lookup a field with an array in nested subdocument mongodb? How to lookup a field with an array in nested subdocument mongodb? mongoose mongoose

How to lookup a field with an array in nested subdocument mongodb?


You can use lookup pipeline to handle nested lookup

const pipeline = [   {     $match: {_id: new mongoose.Types.ObjectId(req.user.userId)}   },   {     $lookup: {       from: 'levels',       let: { level_id: "$teamInfo.challenges.levelId" },       pipeline: [         {           $match: {             $expr: {               $eq: ["$_id", "$$level_id"]             }           }         },         {           $lookup: {             from: '<level collection>',             localField: "levelId",             foreignField: "_id",             as: "levelInfo"           }         },         {           $project: {             levelInfo: {               name: "$levelInfo.name"             }             title: 1           }         }       ],       as: "challenges"     },   },   { $project: {     _id: 1,     fullname: 1,     username: 1,     teamInfo: {       challenges: "$challenges"     }   }}]const result = await User.Aggregate(pipeline)

hope this help !