Model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var CourseSchema = new Schema({
courseCode: {
type: String,
required: true,
unique: true,
},
courseName: {
type: String,
required: 'Course Name cannot be blank',
},
section: {
type: String,
required: 'Section cannot be blank',
},
semester: {
type: String,
required: 'Semester cannot be blank',
},
creator: {
type: Schema.ObjectId,
ref: 'Student'
},
created: {
type: Date,
default: Date.now
}
});
mongoose.model('Course', CourseSchema);
Controller.js
const mongoose = require('mongoose');
const Course = mongoose.model('Course');
const Student = require('mongoose').model('Student');
function getErrorMessage(err) {
if (err.errors) {
for (let errName in err.errors) {
if (err.errors[errName].message) return err.errors[errName].
message;
}
} else {
return 'Unknown server error';
}
};
exports.create = function (req, res) {
const course = new Course();
course.courseCode = req.body.courseCode;
course.courseName = req.body.courseName;
course.section = req.body.section;
course.semester = req.body.semester;
console.log(req.body)
//
//
Student.findOne({studentNumber: req.body.studentNumber}, (err, student) => {
if (err) { return getErrorMessage(err); }
if (!student) {
return res.status(400).send({
message: 'No student found with the given student number'
});
}
//
console.log('student._id',student._id);
req.id = student._id;
console.log('student._id',req.id);
}).then( function ()
{
course.creator = req.id
console.log('req.student._id',req.id);
course.save((err) => {
if (err) {
console.log('error', getErrorMessage(err))
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.status(200).json(course);
}
});
});
};
//
exports.list = function (req, res) {
Course.find().sort('-created').populate('creator', 'firstName lastName fullName').exec((err, courses) => {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.status(200).json(courses);
}
});
};
exports.courseByID = function (req, res, next, id) {
Course.findById(id).populate('creator', 'firstName lastName fullName').exec((err, course) => {if (err) return next(err);
if (!course) return next(new Error('Failed to load course '
+ id));
req.course = course;
console.log('in courseById:', req.course)
next();
});
};
exports.read = function (req, res) {
res.status(200).json(req.course);
};
exports.update = function (req, res) {
console.log('in update:', req.course)
const course = req.course;
course.courseCode = req.body.courseCode;
course.courseName = req.body.courseName;
course.section = req.body.section;
course.semester = req.body.semester;
course.save((err) => {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.status(200).json(course);
}
});
};
exports.delete = function (req, res) {
const course = req.course;
course.remove((err) => {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.status(200).json(course);
}
});
};
//The hasAuthorization() middleware uses the req.course and req.student objects
//to verify that the current student is the creator of the current course
exports.hasAuthorization = function (req, res, next) {
console.log('in hasAuthorization - creator: ',req.course.creator)
console.log('in hasAuthorization - student: ',req.id)
//console.log('in hasAuthorization - student: ',req.student._id)
if (req.course.creator.id !== req.id) {
return res.status(403).send({
message: 'Student is not authorized'
});
}
next();
};
I am able to login and logout. But when I add course it says that id is null. When i print it on console, it looks fine.
What is the problem? i am using ref to allow a student document to make a reference to corresponding course document.
2
Answers
TypeError: Cannot read properties of null (reading '_id')
This error message is telling you that you’re trying to read the
_id
field of an object that isnull
. It also tells you the specific place (line 30, character 43). You need to ensure that you are only accessing fields on objects that exist, which means one of two approaches.Add a safety check before you execute the code, where you ensure that the object exists. You’re already doing this with
if (!student)
but you may need a stronger check. You canconsole.log(student)
to see what the data is looking like if you’re struggling to find the reason for the check failing.Use a default value when the object does not exist. In this piece of code you can’t really continue program execution without a student ID, but using a default value might be helpful for simplifying your error handling. For example, the following code doesn’t need to have the
if(!student)
safety check before the lookup, and can handle students without an ID as well as nonexistent students with the same error. I wouldn’t recommend this for this specific use case but it’s good to know the option exists.Try to create the
course
in the callback, no need to pass the_id
in therequest