Closed harshittpandey closed 5 years ago
That's because there are no params set for username. You can set it to unique in the model schema and drop duplicate. See link below. You can also setup a search function to check the database by username and if input is in database then alert user to enter new username.
Can I use customize express-validator to do that? I've try a few ways but they do not work out. The User.findOne function would not return instantly, cause the registration success.
You need to use a promise, Try this code below, modified from this link :https://stackoverflow.com/questions/35008433/i-am-using-node-js-promise-for-validating-either-username-exist-in-db-or-not
function findUser() {
return User.findOne({"username": req.body.username}).then(function(user) {
if (user.username) {
console.log(user.username);
req.flash('success_msg', 'Username Already Exist, Please Enter a different username');
res.redirect('/users/register');
throw new Error('Username already exists!');
}
// user doesn't exist, all is good in your case
}, function(err) {
// handle mongoose errors here if needed
// rethrow an error so the caller knows about it
throw new Error('Some Mongoose error happened!');
// or throw err; if you want the caller to know exactly what happened
});
}
Then you call the find user function here.
findUser().then(function() { // user doesn't exist, do your stuff User.createUser(newUser, function(err, user){ f(err){ } }); req.flash('success_msg', 'You are registered and can now login'); res.redirect('/users/login'); }).catch(function(err) { // here, you'll have Mongoose errors or 'User already exists!' error console.log(err.message); });
Really hope this helps
many people can register with same username.