Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

561
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda