user2024080 user2024080 - 1 month ago 7x
Node.js Question

Mongoose throw error - how to fix this?

In my app, I am using

to connect with
to post the data. when I use the postman to test the post, I am getting the data updated in the data base. but the console throws this error :

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)

I am not able to understand this error at all. How to fix this? And what is wrong with my code here?

For the reference here is my
api which I am using:

.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, =; {

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:, 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:

  • first line - I included the second parameter, which contains the save family
  • second line - the first condition check if err isn't null
  • last line - I included the newFamily at the response, which is a good practice.