我有这个错误,我似乎无法理解我做错了什么。
在我的数据库中,我有一个名为Question的对象,问题引用了Subject和User。当我试图发布问题我得到一个奇怪的错误。
E11000 duplicate key error index: codenoname.questions.$subject.name_1 dup key: { : null }
我的问题架构:
var questionSchema = mongoose.Schema({
title: { type : String , required : true},
text: { type : String , required : true},
subject: {type:String, ref: 'Subject', required: true},
createdBy: {type: String, ref:'User', required: true},
difficulty: { type : String , required : true},
alternatives: [{alternative: {type:String, required:true}, isCorrect: {type:Boolean, required:true}}]
});
和我的主题
var subjectSchema = mongoose.Schema({
name: { type : String , required : true, unique:true}
});
保存方法:
var question = new Question(
{title: title,
text: text,
subject: ObjectId(subject),
difficulty: difficulty,
createdBy: id,
alternatives:alternatives
});
question.save( function(err, newQuestion) {
if(err) {
res.status(400).json({err:err});
} else {
res.status(200).json({status:"Question added"});
}
});
我尝试了什么
答案 0 :(得分:1)
尝试从主题中删除unique: true
。我认为questionSchema继承了这个独特的属性,一旦你尝试用同一个主题保存两个不同的问题,你就会得到重复的密钥。
请按照以下步骤操作:
unique: true
db.questions.getIndexes()
,找到索引名称。db.questions.dropIndex(name)
来删除它,其中name
是"name"
- 来自第2步的属性我的数据库中的示例,我将从用户名中删除unique-property:
> db.accounts.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "passport_local_mongoose_express4.accounts"
},
{
"v" : 1,
"unique" : true,
"key" : {
"email" : 1
},
"name" : "email_1",
"ns" : "passport_local_mongoose_express4.accounts",
"background" : true
},
{
"v" : 1,
"unique" : true,
"key" : {
"username" : 1
},
"name" : "username_1",
"ns" : "passport_local_mongoose_express4.accounts",
"background" : true
}
]
> db.accounts.dropIndex('username_1')