4

我有一个架构:

  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 }] name: 'MongoError', err: 'E11000 重复键错误索引: testdb.registerinfos.$username_1 dup key: { :空}',代码:11000,n:0,lastOp:0,connectionId:339527,ok:1}

4

2 回答 2

4

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

于 2012-10-19T09:32:43.727 回答
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
        }
    }
});
于 2012-10-19T12:44:34.830 回答