Reputation: 65
Error Image Actually i've an Object in which i have an array of semesters, each semester has an array of subjects and each subject has an array of lessons. I want to add lesson to its respective semester and subject. I use findById to find respective semester from Object but when i use findById again to find particular subject from array of subj's. It gives me error.
Semester.findById(req.body.semesterId).populate({ path: 'subjects' })
.exec((err, model) => {
[model.subjects.findById(req.body.subjectId, (err, model) => {
console.log(model)
})][1]
})
})
Upvotes: 0
Views: 577
Reputation: 733
I would personally structure my Schema's like so:
const semesterSchema = mongoose.Schema({
number: { type: Number, required: true },
subjects: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'Subject' }]
})
const subjectSchema = mongoose.Schema({
semester: { type: mongoose.SchemaTypes.ObjectId, ref: 'Semester', required: true },
title: { type: String },
lessons: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'Lesson' }]
})
const lessonSchema = mongoose.Schema({
semester: { type: mongoose.SchemaTypes.ObjectId, ref: 'Semester', required: true },
subject: { type: mongoose.SchemaTypes.ObjectId, ref: 'Subject', required: true },
title: { type: String },
test: { type: Object }
})
What this does is provides cyclical references to my schemas which is quite nice in some cases.
To solve the case your describing, we could do something like this:
const { semesterId, subjectId } = req.body; // destructure variables needed from body
Semester
.findById(semesterId)
.populate({ path: 'subjects' })
.lean() // use lean() if you only require the document and not the entire mongoose object. i.e. you do not require .save(), .update(), etc methods.
.exec((err, semester) => {
const subject = semester.subjects.find(subject => subject._id === subjectId );
console.log(subject);
});
// ****** THIS ASSUMES YOU HAVE FOLLOWED MY DEFINED SCHEMA ABOVE ********
Alternatively, you could directly query the subject and populate the semester if you want that data like so:
const { semesterId, subjectId } = req.body;
Subject
.findById(subjectId)
.populate({ path: 'semester' })
.lean()
.exec((err, subject) => {
console.log(subject);
});
// ****** THIS ASSUMES YOU HAVE FOLLOWED MY DEFINED SCHEMA ABOVE ********
Upvotes: 1