【问题标题】:Mongoose: uniqueness across several fieldsMongoose:跨多个领域的独特性
【发布时间】:2014-10-18 10:51:18
【问题描述】:

这是我的架构:

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

  email_1: String,
  email_2: String
});

有没有办法确保 email_1email_2 的唯一性?即,如果某些电子邮件被保存为一个用户的email_1,则其他任何人都无法将其保存为email_1email_2。 p>

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

【问题讨论】:

    标签: node.js mongodb validation express mongoose


    【解决方案1】:

    利用数组被索引为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
    

    【讨论】:

    • 谢谢。适用于新数据库,但不适用于我的旧数据库。我是否需要以某种方式重新确保/重置/删除数据库上的索引?
    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多