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

209
Visualizações
How do I check email in backend register

I have a problem with my code now and I can't make it work. I am trying to check if the email added by the user is already in the database so I can generate an error message to the person and I don't know exactly how to check this. Can someone please help me? Thank you so much

Backend code now:

//Create user
app.post("/register/users", (req, res, next) => {
  let userData = {
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  };
  const user = new User(userData);
  user
    .save()
    .then((result) => {
      res.status(200).json(result._id);
    })
    .catch((error) => res.status(422).json(error));
  // console.log(res.body);
});

How can I check if user with similar email is already register to display the error? Thank you so much for your time

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can do a check before saving the user.

First, check if the user with the same email exists in the database. If exist, do not save again, instead send the response. If not exist, save the user.

app.post("/register/users", async (req, res, next) => {
  let userData = {
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  };
  // checkin if a user with the mail exist
  try {
    const existingUser = await User.findOne({ email: req.body.email });
    if (existingUser) {
      // you may want to send different status code
      return res.status(200).json({ message: 'User alreay registered });
    }
    const user = new User(userData);
    // save the user
    const newUser = await user.save();
    return res.status(200).json(newUser._id);
  } catch(error) {
    return res.status(422).json({ error });
});
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