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

9

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.

Buhr answered 17/1, 2022 at 9:32 Comment(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.South
D
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 ;)

Dunsany answered 17/1, 2022 at 9:41 Comment(0)
B
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

Break answered 18/4, 2022 at 19:50 Comment(0)
S
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.

Saltish answered 15/3, 2023 at 0:45 Comment(0)
E
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.

Errolerroll answered 22/3 at 11:30 Comment(0)
H
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
Hanyang answered 23/3, 2023 at 14:20 Comment(0)
P
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.

Pleasance answered 10/8, 2023 at 2:46 Comment(0)
P
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.

Predicament answered 13/11, 2023 at 14:22 Comment(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.Soutache
T
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

Tafoya answered 17/1 at 3:41 Comment(0)
G
-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!

Garry answered 31/3, 2022 at 5:22 Comment(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.Soutache

© 2022 - 2024 — McMap. All rights reserved.