我在 mongodb 集合上创建了一个稀疏且唯一的索引。
var Account = new Schema({
email: { type: String, index: {unique: true, sparse: true} },
....
它已正确创建:
{ "ns" : "MyDB.accounts", "key" : { "email" : 1 }, "name" : "email_1", "unique" : true, "sparse" : true, "background" : true, "safe" : null }
但是,如果我插入第二个文档且未设置 key ,则会收到此错误:
{ [MongoError: E11000 duplicate key error index: MyDB.accounts.$email_1 dup key: { : null }]
name: 'MongoError',
err: 'E11000 duplicate key error index: MyDB.accounts.$email_1 dup key: { : null }',
code: 11000,
n: 0,
ok: 1 }
有什么提示吗?
最佳答案
我也刚刚遇到这个问题。我想要一个值要么为空,要么是唯一的。因此,我设置了 unique
和 sparse
标志:
var UserSchema = new Schema({
// ...
email: {type: String, default: null, trim: true, unique: true, sparse: true},
// ...
});
并且,我确保数据库实际上已使用 db.users.getIndexes();
正确创建了索引
{
"v" : 1,
"key" : {
"email" : 1
},
"unique" : true,
"ns" : "test.users",
"name" : "email_1",
"sparse" : true,
"background" : true,
"safe" : null
},
(所以,这与此处的问题不相同:mongo _id field duplicate key error)
我的错误是将默认
值设置为null
。从某种意义上说,Mongoose 将显式 null
视为必须唯一的值。如果该字段从未定义(或未定义
),则不会强制该字段是唯一的。
email: {type: String, trim: true, unique: true, sparse: true},
因此,如果您也遇到此问题,请确保您没有设置默认值,并确保您没有在代码中的其他任何地方将值设置为 null
。相反,如果您需要显式设置它,请将其设置为未定义
(或唯一值)。
关于Mongodb唯一稀疏索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17125089/