我得到一个重复的键错误索引:当我尝试在mongodb中保存数据时

时间:2012-10-19 08:48:03

标签: node.js mongodb express mongoose

我有一个架构:

  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重复键错误索引:testdb.registerinfos。$ username_1 dup key:{:null}]   名称:'MongoError',   错误:'E11000重复键错误索引:testdb.registerinfos。$ username_1 dup key:{:null}',   代码:11000,   n:0,   lastOp:0,   connectionId:339527,   好的:1}

2 个答案:

答案 0 :(得分:3)

您对registerinfos.username有一个唯一约束,并且您正在尝试保存一个文档,该文档具有该数据库中已存在的字段的值。我知道这是因为它在异常中说的是;)它与_id值无关。

答案 1 :(得分:2)

Sammaye指出,每次调用savePersonalInfo时,您的代码都会尝试创建一个新的RegisterInfo文档。如果您还使用此功能更新现有文档,则需要修改此功能。

在伪代码中:

RegisterInfo.findOne({Username: req.body.regUserName}, function (err, reginfo) {
    if (!err) {
        if (!reginfo) {
            // Doesn't exist, create new doc as you're doing now
        } else {
            // Does exist, update reginfo with the values from req.body and then
            // call reginfo.save
        }
    }
});