Question 34 / 50
ImportantEasyScenarioIndexing
How would you prevent two users from registering with the same email?
Think about it first.
Short answer
Create a unique index on email. Application checks are not enough under concurrency — the index is the guarantee. Handle duplicate-key errors on insert as 'email taken'.
Why?
A unique index can be sparse or partial if some documents have no email. For case-insensitive emails, index a normalised field (lowercase) rather than hoping a unique index on mixed case will do what users mean.
Example
db.users.createIndex({ email: 1 }, { unique: true })Interview tip
Mention the race: two requests both find no user, both insert. The unique index is the lock.
Common mistake
findOne({ email }) then insertOne, calling that 'validation'.
How did you do?
Learn
Cheat Sheet