【发布时间】:2012-10-09 20:24:24
【问题描述】:
我有一个架构:
var RegisterInfoSchema= new Schema({
Organization:String,
NGOName:String,
Acronym:String,
Address:String,
Province:String,
District:String,
Tehsil:String,
Telephone_number:String,
Website:String,
Demographics:String,
Username:{type:String ,index: {unique:true}},
Password:String
})
exports.savePersonalInfo = function (req,res){
console.log("savePersInfo CALLED");
var receivedObj = new RegisterInfo({
Organization: req.body.regOrgType ,
NGOName: req.body.regName,
Acronym: req.body.regAcronym ,
Address: req.body.regAddress ,
Province: req.body.regProvince,
District: req.body.regDistrict,
Tehsil: req.body.regTehsil ,
Telephone_number: req.body.regTelNo ,
Website: req.body.regWebAddr,
Demographics: req.body.regDemographics,
Username: req.body.regUserName ,
Password: req.body.regPsw
});
receivedObj.save(function(err){
console.log("inside Save ");
if(err){
console.log(err);
}
else{
console.log("Saved!!");
res.send("");
}
});
}
用户名中有索引 当我尝试使用 save() 方法保存数据时,会出现以下错误:
{ [MongoError: E11000 duplicate key error index: testdb.registerinfos.$username_1 dup key: { : null }] 名称:'MongoError', err: 'E11000 重复键错误索引:testdb.registerinfos.$username_1 dup key: { : null }', 代码:11000, n: 0, 最后操作:0, 连接ID:339527, 好的:1 }
【问题讨论】:
-
可能是_id未设置,所以它认为它是一个新行
-
我应该自己指定 id 吗? @Sammaye
-
您应该不需要指定_id,当您收到此错误时,您使用的是什么代码?您确定这不是您尝试创建新行的时候吗?因为如果在您尝试创建新行时发生这种情况,那么它是因为 c 的索引
-
我更新了一个使用值保存在数据库中的代码@Sammaye
-
是的,我相信这是因为您每次都在创建一个新行并且输入相同的数据,因此您不能有重复的用户名。
标签: node.js mongodb express mongoose