Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
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 });
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!