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.