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

274
Visualizações
How to check if user already exists before regisration?

Hello i want to check out if user exist before registration, but of some reason it does't works. something wrong is happening after else. Can some one tell me why? thank you.

//jj. using express
const app = express()
import express, { json } from 'express'

//jj. main array
const allUsers = [{name:"jane"},{name:"jacek"},{name:"morty"}];


//jj. main listener
app.post('/adduser', (req, res) => {
  let tocomapre = req.body.name 
  for (let user of allUsers ){
    if(user.name == tocomapre){
      console.log(user.name, req.body.name, tocomapre);
      console.log('user already exist');
      res.status(400).send("User alredy exist")
      break
    }
    else{
      try{
        const user = {name:req.body.name}
        console.log(req.body.name);
        allUsers.push(user)
        return res.status(200).send('user on board')
      }catch{
        res.status(500).send(" it's ain't good sthww")
      }
    }
  }
});

======================================================
//jj. request

POST http://localhost:3000/adduser
Content-Type: application/json

{
    "name":"morty"
}

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You have the else inside the for loop so that a new user is pushed to allUsers if it merely differs from the first existing user. This is wrong.

Replace the break with a return and put the try-catch block after the loop:

let tocomapre = req.body.name 
for (let user of allUsers){
  if(user.name == tocomapre){
    ...
    return
  }
}
try{
  ...
}catch{
...
}

If the new user is found at any point during the for loop, you issue a 400 error and return. Otherwise you add the user.

over 4 years ago · Santiago Trujillo 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