0

I have created schema like below

var TeamSchema = new Schema({
    name: {
        type: String,
        default: '',    
        unique : true
      },
      location: {
        type: String,
        unique: true
      }
};
mongoose.model('Team', TeamSchema);

In above for Location attribute unique:true by mistake. After that I removed unique:true and tried to add data but still it throws following error.

errmsg: 'E11000 duplicate key error index: Hackathon.teams.$location_1 dup key: { : "Bangalore" }'

How to solve this and How to handle schema If I want to add More fields ?

Praveenkumar
  • 921
  • 1
  • 9
  • 28
  • check the indices that are set in mongodb using db.collection.getIndexes() and drop unwanted indices – Narayansingh Rajput Jan 29 '16 at 10:22
  • Did you remove the old "Bangalore" after you changed unique. Also if you want to add more fields I just add more fields to the schema that has worked for me in the past manually. The following link might show a better way. using schema.add() http://mongoosejs.com/docs/api.html#schema_Schema-add – jack blank Jan 29 '16 at 10:24
  • @jack blank adding new fields worked but changes in existing attributes not working. – Praveenkumar Jan 29 '16 at 10:32
  • @NarayansinghRajput I used to work in rails there we will make changes through code only. Is there any other way through Migrations. – Praveenkumar Jan 29 '16 at 10:33
  • are you using mongo native package in your code or just mongoose – Narayansingh Rajput Jan 29 '16 at 10:52
  • Just Mongoose not the mongo package( I wish to use orm like thing) – Praveenkumar Jan 29 '16 at 10:57
  • check this link if its helpful http://stackoverflow.com/questions/12193591/see-existing-indexes-in-mongodb-using-mongoid – Narayansingh Rajput Jan 29 '16 at 11:00
  • I came across a similar error. I dropped my collection and was able to update the proper field but when I tried to do it again I got the same error. my problem was that I had `_id` being the same all the time on save and that caused a duplicate error. maybe your collection still thinks that `location` has to be unique like my `_id` so drop the collection and start over or maybe this will help interpret your error and provide an alternative solution. It did for me. http://stackoverflow.com/a/24430345/1893672 – jack blank Jan 30 '16 at 04:36
  • Thanks Everyone for their suggestion. I went with NarayanSingh suggestion of drop the index using mongo shell. – Praveenkumar Feb 01 '16 at 04:55

0 Answers0