Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!