当前位置: 首页 > 知识库问答 >
问题:

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

宗政法
2023-03-14

我有一个模式:

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

共有2个答案

朱运诚
2023-03-14

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
        }
    }
});
嵇丰
2023-03-14

您对registerinfos有唯一的约束。用户名,并且您试图保存一个文档,该文档具有数据库中已存在的该字段的值。我知道这一点,因为它在例外中就是这么说的;)它与_id值无关。

 类似资料: