猫鼬:几个领域的独特性

时间:2014-08-25 09:57:25

标签: node.js mongodb validation express mongoose

这是我的架构:

var user = new Schema({
  // other fields...

  email_1: String,
  email_2: String
});

有没有办法确保 email_1 email_2 的唯一性?也就是说,如果某个电子邮件保存为一个用户的 email_1 ,则其他人无法将其保存为 email_1 email_2

我尝试过复合索引,但它只检查电子邮件对,我需要所有电子邮件都是唯一的。

1 个答案:

答案 0 :(得分:2)

使用数组被编入索引为multikey indexes的事实,并将您的电子邮件存储为"有序对" [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