Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

286
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda