Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch errorcode in mongoose

Just playing around with my first login system, based on nodejs/express/mongoose/passport.

I have found more posts about this subject, but they all are slightly different then mine.

model:

module.exports = mongoose.model('User',{
id: String,
username: String,
password: String,
email: { type: String, unique: true }
});

For username a query is used to check if username is already taken. But that is not the way to do it. I have learned the database itself must check this. So that is why I am trying it out on the email field.

saving a new user:

// save the user
                    newUser.save(function(err) {
                        if (err){
                            console.log('Error in Saving user: '+err);  
                            //throw err; // server stops working immediately!!
                            return done(null, false, req.flash('message','DB error...'));
                        }
                        console.log('User Registration succesful');    
                        return done(null, newUser);
                    });

I added slashes before "throw err", because the node server stops immediately when trying to "throw". I copied/pasted the return done(...) part, which works well.

console error message:

 Error in Saving user: MongoError: insertDocument :: caused by :: 11000 
 E11000 duplicate key error index: mydb.users.$email_1  dup key: { : 
 "[email protected]" }

Problem: If any database error occures, I cannot assume it always will be a duplicate insert error, so I need to check on this, so I can show a message about duplicate emailadres or another usefull message.

I can't find anything like:

if(errorcode == E11000)
 message="duplicate email"
else
    message="an error occured bla bla"
like image 985
Terradon Avatar asked May 19 '26 00:05

Terradon


1 Answers

The error code is stored in err.code, so you can check for it like this:

if (err) {
  if (err.code && err.code === 11000) {
    message = "duplicate email";
  } else {
    message = "an error occured bla bla";
  }
}
like image 70
robertklep Avatar answered May 20 '26 16:05

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!