'Express: Variable not getting rewritten
I have this JS code that I've been looking at for the past 2 hours and cannot find the reason why the variable "message" doesn't get rewritten to "User already exists.". The thing is that "Inside first if" runs, but the variable message doesn't get rewritten to "User already exists."
async function postRegister(req, res) {
const familyName = req.body.familyName;
const email = req.body.email;
const password = req.body.password;
const repeatPassword = req.body.repeatPassword;
let message = 'msg';
// Check if user already exists
await db
.promise()
.query(
'SELECT * FROM users WHERE email = ?',
[email],
function (err, results) {
if (results.length > 1) {
console.log('Inside first if');
message = 'User already exists.';
return;
} else {
if (password !== repeatPassword) {
console.log('passwords do not match');
} else {
const newUser = new User(familyName, password, email);
newUser.save();
res.redirect('/login');
}
}
}
);
console.log(message);
res.render('authentication/register', { message: message });
}
Solution 1:[1]
Try this. Do not find all the users. Find only one since there will not be any duplicate entry.
try {
const user = await User.findOne({ email: email})
let message = ''
if(user) {
message = 'User already exists'
// better return the response here
}
if (password !== repeatPassword) {
message 'passwords do not match'
}
if(message) {
// Some error message is present, perform your action here
}
// Create your user
res.redirect('/login')
} catch(err) {
console.log(err)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | iTR |
