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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With