Search code examples
node.jsmongodbmongoosemongoose-schema

unable to find subdocument using mongoose


I wanted to find the subdocument with id and return the subdocument, not the parent document, my schema are as follows :

var coursesSchema = new mongoose.Schema({
 coursename:{type:String}
});

var parentSchema = new mongoose.Schema({
 courses:[coursesSchema]
});

var Parent= mongoose.model('parent', parentSchema );
module.exports = Parent;

let data = Parent.courses.id(_id);

as given in the docs I tried to find the subdocument using .id, it is throwing error saying Cannot read property 'id' of undefined,

and after searching a lot found this question I tried the same, apparently it also returned the same error.

let data = Parent['courses'].id(_id);

please help me with this, I am not able to get my head around with it🙏


Solution

  • We can solve this using Aggregation operations as @KunalMukherjee pointed out in the comments Here is a quick example to do so