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

452
Visualizações
Efficient way to check if username/email already exist in MongoDB for registration

I'm in a NodeJS server using ExpressJS to handle my /register route. One step in my registration process is to ensure that the user's username and email are both unique, if so, they can register and add their account to the users collection.

Currently, my code is as follows for this "checking if username/email exists" step:

// Checking is user already exists (username & email)
try {
    const usernameExists = await User.findOne({username: req.body.username});
    const emailExists = await User.findOne({email: req.body.email});
    if (usernameExists && emailExists) return res.status(400).send("Username and email already taken");
    if (emailExists) return res.status(400).send("Email already taken");
    if (usernameExists) return res.status(400).send("Username already taken");
} catch (e) {
    return res.status(500).send("Error querying DB to check if username/email exists or not");
}

This feels highly inefficient as I'm doing two queries to the database. Is there anyway to combine the two User.findOne... queries? Or is this how this task is supposed to be done?

Thanks so much!

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

0

You can check for unique values in schema itself, just add unique in schema for the field you want. Like this

email:{
   unique:true,
   required:true,
},
username:{
   unique:true,
   required:true,
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You could use $or

await User.findOne({
  $or: [{ username: req.body.username }, { email: req.body.email }],
})
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