Indexing
Unique Indexes
Enforce uniqueness in the database, not only in application code.
A unique index is a constraint. Two documents cannot share the same key. _id already is one. email on users should be another — a race between two signups is a duplicate key error, not a 'check in Node then insert'.
db.users.createIndex({ email: 1 }, { unique: true })
db.cartItems.createIndex({ userId: 1, sku: 1 }, { unique: true })Missing and null count as a value. Two documents with no `email` violate { email: 1 } unique. Old fix: sparse: true (index only docs that have the field). Better: partialFilterExpression: { email: { $type: "string" } } so only real emails are unique. Unique does not make a bad email format valid — that is schema validation.
Interview question
How do you enforce a unique email in MongoDB?
A unique index on email. Application checks race. Duplicate key 11000 is the conflict. Unique treats missing/null as a value — only one document can omit the field unless I use a partial (or sparse) index so only actual emails are indexed.