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

166
Visualizações
Preserve atomicity in a register function with conditional insert

I'm building a web application. In the register function, I first check whether the username or email that was passed is already in use by an existing user. If not, then I do an insert operation, therefore creating the new user. Now let's imagine 2 register requests are sent exactly at the same time. Both determine that the new username and email are valid, therefore creating 2 users. How could I make sure that there can't be multiple users inserted even if 2 equal operations are run at the same time? Should I use indexes, or is there a 'conditional' insert function?

const already_exist = await db.users.findOne({$or: [{ username }, { email }]});
if(!already_exist) {
    // FIXME: Only insert if username and email are not present in the database already
    const registered = await db.users.insertOne({username, email});
}

I know that it's close to impossible that this would ever happen, especially given how nodejs is single-threaded, however, I might expand to multiple nodes in the future and I want to make sure that this can never happen.

about 4 years ago · Juan Pablo Isaza
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