猫鼬重复键错误,字符串为空

时间:2019-02-19 07:30:18

标签: javascript mongodb mongoose mongodb-query mongoose-schema

我有一个这样的架构:

const MemberSchema = mongoose.Schema({
  name: {
    type: String,
  },
  email: {
    type: String,
    unique: true
  },
  phone: {
    type: String,
    unique: true
  }
})

当然,电子邮件和电话必须是唯一的,但电子邮件或电话是可选的,因此它们可以为空字符串。

当您将它们设置为唯一索引时,会出现此错误

E11000 duplicate key error collection: model.members index: email_1 dup key: { : "" }'

是否可以将异常添加到唯一性?

修改

我像下面那样更改了代码,但仍然无法正常工作。

email: {
    type: String,
    trim: true, index: true, unique: true, sparse: true
  },

\

'E11000 duplicate key error collection: email-collector.members index: email_1 dup key:{ : null }'

当我运行getIndexes时,我得到了

> db.members.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "email-collector.members"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "email" : 1
                },
                "name" : "email_1",
                "ns" : "email-collector.members",
                "sparse" : true,
                "background" : true
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "email" : 1,
                        "phone" : 1
                },
                "name" : "email_1_phone_1",
                "ns" : "email-collector.members",
                "sparse" : true
        }
]

0 个答案:

没有答案