7

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.

1
  • 1
    It seems you don't have username as a part of your schema and you have created an index on it. Please make a change on schema or drop index on the username. Commented Jan 17, 2022 at 9:54

9 Answers 9

11

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

0
4

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

1

In my case dropping users' collection helped.

To drop a user's collection in MongoDB, there are a few different methods, but one simple way is to:

  1. Log in to your MongoDB account and navigate to your project.
  2. Click "Browse Collections" and find the collection you want to delete.
  3. Hover over the name of the collection to reveal a trash bin icon on the right-hand side. Click this icon to delete the entire collection.

If you don't see the trash bin icon, it may be because you don't have the necessary permissions. This can happen if you're working as part of a team and someone else added you to the project. In this case, you can ask the team member who has the necessary permissions to delete the collection for you.

Once you've dropped the collection, you should be able to register users through Postman without any issues.

1

It is as easy as changing the collection name in your connection string and dropping the existing one to avoid wasting time, as I was experiencing the same problem.

0
  1. Export the collection and store it safely
  2. Drop the collection
  3. Create a new collection with the same name as before
  4. Import the stored collection
0

I came across same:

error-MongoServerError: E11000 duplicate key error collection: OauthDB.oauthentications index: username_1 dup key: { username: null }

So, I tried finding the index in Mongosh by calling:

db.collection.getIndexes()

on (oauthentications) collection.And I got result as below -

{
  v: 2,
  key: { username: 1 },
  name: 'username_1',
  background: true,
  unique: true
}

I don't require username in my existing project so I call

db.oauthentications.dropIndexes("username_1")

And it solves the problem for me.

0

=> Check The projects database in the mongoDB, and verify how many indexes are available. => If you have more >1, delete all except the id.

Better still, you can recreate the collection again, by importing it.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Nov 14, 2023 at 11:08
0

This happens because you might be using previously created collection name i.e. Users and at that time you might also be expecting username (required field) from the user but in current schema, you are not taking username as required field or not taking username at all and when you try to save current object, mongo will validate and gives you error for not passing username. To get rid of this, do check indexes and remove the field which are not to be stored.

screenshot

-1

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!

1
  • 2
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Mar 31, 2022 at 6:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.