Here's my schema:
var user = new Schema({
// other fields...
email_1: String,
email_2: String
});
Is there a way to ensure uniqueness of both email_1 and email_2 ? Ie., if some email is saved as email_1 of one user, it can not be saved as email_1 or email_2 by anyone else.
I've tried compound index, but it only checks for email pairs, and I need all emails to be unique.
Use the fact that arrays are indexed as multikey indexes and store your emails as an "ordered pair" [email1, email2]
:
> db.emails.ensureIndex({ "emails" : 1 }, { "unique" : true })
> db.emails.insert({ "emails" : ["me@wdb.com", "metoo@wdb.com"] })
> db.emails.insert({ "emails" : ["you@eagor.com", "me@wdb.com"] }) // MongoDB says NO!
> db.emails.insert({ "emails" : ["metoo@wdb.com", "myself@wdb.com"] }) // MongoDB says NO