Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Item Atomicity

I'm trying to create a new account with unique email. One of the options is to check if there is an account with the same email already exists. If there is none, create the new account.

Account
    .find({email: req.body.email})
    .exec((err, accounts) => {
        //Try to find an account that have the same email
        if (!accounts.length) {
          //If none is found create a new account with this email
          var account = new Account({email: req.body.email});
          account.save();
        }
    });

The problem with this approach is that I am unclear about whether this is atomically-safe or not. What if multiple users trying to create a new account with the same email at the same time. Will that ruin the consistency of my database ?


I've heard about the unique option in SchemaType.
Should I go with that option instead ?
Is using the mongoose built-in validation a must ? Other options ?
Is the above code considered bad practice ?
like image 491
rocketspacer Avatar asked Dec 13 '25 02:12

rocketspacer


1 Answers

This will not be atomically safe in MongoDB. You can however use a unique index on the email field. This will cause an insert to fail if it was used already or if someone just inserted it concurrently.

If you plan on using sharding this can become a problem because unique indexes are only supported on shard keys.

like image 157
Erik Avatar answered Dec 16 '25 07:12

Erik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!