'How can I solve a "MongoError: E11000 duplicate key error collection" error in Mongo?

I have created a new Mongo collection to a new project, but when I try to create a new user, I get the following error:

MongoError: E11000 duplicate key error collection: GestorMedico.users index: username_1 dup key: { username: null }

My User schema is the following:

const { Schema, model } = require("mongoose");

const userSchema = new Schema({
    nombreEmpresa: {
        type: String,
        unique: true,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    telefono: {
        type: String,
        required: true
    },
    contraseña: {
        type: String,
        required: true
    }
}, {
    timestamps: true,
    versionKey: false
});

module.exports = model("Users", userSchema);

My function is the following:

userCtrl.createUser = async (req, res) => {
    const newUser = new User(req.body);
    
    newUser.contraseña = await crypt.encryptPassword(newUser.contraseña);
    
    await newUser.save();
    
    res.status(200).json({
        status: "OK",
        message: "User created"
    });
};

And my collection looks like:

enter image description here

I have reused the backend of one of my old projects, which have a "username" in a schema.



Solution 1:[1]

The Error E11000 is thrown when there are unique fields (indexes) that you try to save while there is another one already in the Database.

since the field seems to be username which is not visible in the userSchema, I am assuming you still have that index existing in your Database.

In mongo Compass on the page u made a screenshot from, go to the tab "Indexes", refresh and delete the username index in case it is there.

If that does not solve it proceed to print out the indexes via code and check there, if there is one that your don't want use db.collection.dropIndex() to delete it. Docs here

Also make sure that in your req.body the nombreEmpresa field is transferred since it is required when you want to save the document.

I hope that solves it ;)

Solution 2:[2]

you set username index as unique property so you have to use this:

db.user.dropIndex()

or when you are in user collection in compass you can delete your indexes from tabs above of collection Shot

Solution 3:[3]

this problem is raised when atleast once we do unique: true, if u remove this option error will still persists, I solved this problem by dropping collection. if u want again the same collection u can insert document and the same collection will be created without having this error.

Thanks!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maximilian Dolbaum
Solution 2 mohammad tavassolian
Solution 3 RAMAKANT SINGH YADAV