Home > Mobile >  how to solve " duplicate key error collection: xxxxxxx.users index: name_1 dup key: { name: nul
how to solve " duplicate key error collection: xxxxxxx.users index: name_1 dup key: { name: nul

Time:11-05

I am trying to insert into mongodb from nodejs

My model

const UserSchema = new mongoose.Schema({
    surname:{
        type: String,
        required: true,
    },
    firstName:{
        type: String,
        required: true,
    },
    password:{
        type: String,
        required: true,
    },
}, {timestamps: true})

When I insert the first user it works well but if I try creating another user I will get the following error

E11000 duplicate key error collection: xxxxxxx.users index: name_1 dup key: { name: null }

but I dont have name_1 index on my model.

How do I solve this problem?

CodePudding user response:

It seems like at some point in your past, you had

{
   name: String,
   required: true,
   unique: true
}

On your model, and have since removed it. By adding that

db.collection.dropIndex('name_1') should do the trick, or if you have a UI like Mongo Compass, you can drop it from the UI as well.

  • Related