In my app, I am using
mongoose
mlab
events.js:141
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'code' of null
at C:\Tutorials\try\NodePractical\MEAN-Family\app\routes\api.js:42:13
at C:\Tutorials\try\NodePractical\MEAN-Family\node_modules\mongoose\lib\model.js:3336:16
at C:\Tutorials\try\NodePractical\MEAN-Family\node_modules\mongoose\lib\document.js:1927:18
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)
post
.post(function( req, res ){
var family = new Family();
family.username = req.body.username,
family.password = req.body.password,
family.familyLeader = req.body.familyLeader,
family.husband = req.body.husband,
family.wife = req.body.wife,
family.kids = req.body.kids;
family.save(function(err) {
if (err.code == 11000) {
return res.json({ success: false, message: 'A user with that username already exists. '});
}
else {
res.send( err );
}
res.json({ message: 'Family created!' });
});
})
Because every node callback have this signature callback(error, response)
,
this means that if an error occurs, the first parameter will contain the error and the second will be null. But if no error occurs, the first parameter will be null, which mean that in this case you're trying to access the property .code
of a null variable.
To prevent this, you can first check if error isn't null, by doing this:
family.save(function(err, newFamily) {
if (err) {
if(err.code == 11000) {
return res.json({ success: false, message: 'A user with that username already exists. '});
}
else {
return res.send( err );
}
}
res.json({ message: 'Family created!', newFamily: newFamily });
});
Pay attention to the changes:
err
isn't nullnewFamily
at the response, which is a good practice.