how to recover from duplicate key in mongoose + express

Try this:

user.save(function(err){
  if ( err && err.code !== 11000 ) {
    console.log(err);
    console.log(err.code);
    res.send('Another error showed up');
    return;
  }

  //duplicate key
  if ( err && err.code === 11000 ) {
    req.flash('error', 'User already exists');
    res.redirect('/signup');
    return;
  }

  res.locals.user = user;
  req.session.user = user;
  //res.locals.session = req.session;
  res.redirect('/');
});

You won't fill the error log this way.


I have not tried this yet, but this is what I'm thinking will avoid causing an error:

//look for existing user first
user.findOne({ username: req.body.username }, function(err, user) {
  if ( err ) throw err;

  //existing user found, stop registration
  if ( user ) {
      res.flash('error', "That user already exists");
      res.redirect('/signup');
      return;
  }

  //create new user
  var user = new User({ username: req.body.username });

  user.save(function(err){
   if ( err ) throw err;
      res.flash('info', "Your account has been created");
      res.redirect('/account');
  });
});