架构(../models/add.js)使用稀疏:真仍然得到MongoError:E11000重复键错误
var addSchema = new Schema({
name: {type: String, unique: true, sparse: true},
phone: Number,
email: String,
country: Number
});
module.exports = mongoose.model('Contact', addSchema);
附加manager.js
var Add = require('../models/add.js');
var AM = {};
var mongoose = require('mongoose');
module.exports = AM;
AM.notOwned = function(country, callback)
{
Add.update({country: country}, {country: country}, {upsert: true}, function(err, res){
if (err) callback (err);
else callback(null, res);
})
}
news.js
// if country # is not in the database
AM.notOwned(country, function(error, resp){
if (error) console.log("error: "+error);
else
{
// do stuff
}
})
错误:
MongoError: E11000 duplicate key error index: bot.contacts.$name_1 dup key: { : null }
看到错误信息后,我搜索了一下,并了解到在创建文档时,由于未设置名称,因此将其视为空。 See Mongoose Google Group Thread第一次调用AM.notOwned时,它将工作,因为集合中没有任何文档没有名称键。 AM.notOwned将随后插入带有ID字段和国家字段的文档。
随后的AM.notOwned调用失败,因为已经有一个没有名称字段的文档,因此它被视为name:null,而第二个AM.notOwned被调用失败,因为未设置字段“name”并被处理也为null;因此它不是唯一的。
因此,遵循Mongoose线程的建议并阅读mongo docs,我使用sparse:true来查看。但是,它仍然抛出同样的错误。进一步研究它,我认为它可能与以下问题相同:this,但将模式设置为name:{type:String,index:{unique:true,sparse:true}}也不修复它。
This S.O.问题/答案使我相信这可能是由索引不正确引起的,但我不太清楚如何从Mongo控制台读取db.collection.getIndexes()。
db.contacts.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "bot.contacts",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"name" : 1
},
"unique" : true,
"ns" : "bot.contacts",
"name" : "name_1",
"background" : true,
"safe" : null
}
]
我能做些什么来解决这个错误?
db.contacts.dropIndex()工作。虽然,我尝试使用db.contacts.reIndex(),并没有解决它。感谢您提供的简明扼要的答案。我不能为了我的生活找出我做错了什么,到处搜寻。 – thtsigma 2013-02-22 17:08:32