Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda