const skillsSchema = {
title: String,
description: String,
};
const Skill = mongoose.model('Skill', skillsSchema);
const teacherSchema = {
profession: String,
teacherFName: String,
bornDate: Number,
priceperhour: Number,
videolink: String,
email: String,
password: String,
skills: [skillsSchema],
};
const Teacher = mongoose.model('Teacher', teacherSchema);
app.post('/taddcourse', function (req, res) {
const title = req.body.courseTitle;
const discription = req.body.courseBody;
const teacherName = req.body.teacher;
const skill = new Skill({
title: title,
description: discription,
});
Teacher.findOne({ teacherFName: teacherName })
.then(function (foundTeacher) {
foundTeacher.skills.push(skill);
foundTeacher.save();
res.render('teacherdash', {
teachName: foundTeacher.teacherFName,
courses: foundTeacher.skills,
});
})
.catch(function (err) {
console.log(err);
});
});
when I try to run the code this error appears
TypeError: Cannot read property ‘skills’ of null.
I want to push a skill for each teacher in this line
foundTeacher.skills.push(skill);
but I dont know why this error appears
2
Answers
It seems like no object was found with provided teachername. Try checking the name in the database also the err object
You should make the following changes:
1-) You need the setup schemas using
new mongoose.Schema(...)
2-) To add a skill to a teacher you can use
findOneAndUpdate
with the push operator.