I've created a signup form using mongoose and express 3
Its possible the user already exists with that username, in which case I get an err.code 11000 (duplicate key). How should I handle existing users?
This is what I'm doing now....but I'm not sure checking error code is best way:
user.save(function(err){
if ( err ) {
console.log(err);
console.log(err.code);
//duplicate key
if ( 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('/');
});
Is there a better way of doing this?
If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error. You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.
Before we keep going. 1- name { type :string , unqiue: true} unique param in mongoose is not a validator meaning doing const myUser = new User(data) will not throw an error in case of duplication. 2- when trying to add a user I suggest using either insertOne or create function.
If you ever faced this error all you need to do is to check your model carefully and find out that is there any unique key set true by you and if it is not necessary then simply remove the unique key from the model or otherwise set a unique value if it is necessary to be unique.
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');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With