当我第二次尝试插入没有昵称的文档时,出现 MongoDB 错误。该文档已具有唯一字段且非必需。
这是我的 Mongoose 模型:
var schema = new Schema ({
username: {
type: String,
required: false
},
nickname: {
type: String,
required: false,
unique: true,
trim: true
},
status: {
type: String,
required: false,
trim: true,
minlength: 1,
maxlength: 100
},
avatar: String,
online: {
type: Boolean,
default: false
},
created: {
type: Date,
default: Date.now
},
device: {
type: ObjectId,
ref: 'Device',
required: false
},
createdRooms:[{
type: Schema.Types.ObjectId,
ref: 'Room'
}],
facebook: {
facebookToken: {
type: String,
required: false,
trim: true,
unique: false
},
facebookId: {
type: String,
required: false,
trim: true,
unique: false
}
}
},
{
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
第一次将没有昵称的文档添加到数据库中,但是当我想保存另一个没有昵称的文档时,出现错误:
MongoError: E11000 duplicate key error collection: grooptag.users index: nickname_1 dup key: { : null }
最佳答案
所以我查找了“MongoDB不是必需的,但是是唯一的”,我发现了这个:mongoDB/mongoose: unique if not null
看来您需要使用 sparse: true
而不是 required: false
来获得您想要的内容。
编辑:阅读有关稀疏索引的 MongoDB 文档,但是,我被重定向到部分索引,这似乎是从 MongoDB 3.2 开始的方法:https://docs.mongodb.com/manual/core/index-partial/#index-type-partial
问题是,虽然文档明确指出:
Partial indexes represent a superset of the functionality offered by sparse indexes and should be preferred over sparse indexes.
对于稀疏索引和唯一索引来说似乎并非如此,因为它们也在同一页面上声明:
A partial index with a unique constraint does not prevent the insertion of documents that do not meet the unique constraint if the documents do not meet the filter criteria.
自相矛盾的方式...:/
关于javascript - 具有唯一字段的重复键错误集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39698482/