Node.js – I am getting a duplicate key error index: when I am trying to save data in mongodb

expressmongodbmongoosenode.js

I have a schema :

  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("");

    }

   });
   }

There is indexing in Username
When I am trying to save data using save() method then it gives the following error:

{ [MongoError: E11000 duplicate key error index: testdb.registerinfos.$username_1 dup key: { : null }]
name: 'MongoError',
err: 'E11000 duplicate key error index: testdb.registerinfos.$username_1 dup key: { : null }',
code: 11000,
n: 0,
lastOp: 0,
connectionId: 339527,
ok: 1 }

Best Answer

You have a unique constraint on registerinfos.username and you're trying to save a document that has a value for that field that already exists in the database. I know this because that's what it says in the exception ;) It has nothing to do with _id values.

Related Topic