node

How to fix MongoError:e11000 duplicate key error collection


In this article, you are going to learn about how to fix MongoError:e11000 duplicate key error collection.

Working in a NoSQL database gives you much flexibility but sometimes, this can be the reason for getting yourself in an unwanted situation like MongoError:e11000 duplicate key error collection. It is a common MongoDB error and occurs for a very simple reason. I was facing this error while working with Nodejs and Mongoose. If you are facing the same problem and don’t know how to fix it then this article is for you. I will share my experience of how I get into this error and the solution for it. Let’s see the error first:

You can see that I was getting duplicate key errors while I was trying to register the account with the same email. But I want to get rid of this and want to register multiple accounts with this same email. The main reason of getting this error is that I set a MongoDB unique key : true. See the code example:

const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
    email : {
        type : String,
        unique : true
    },
    password : {
        type : String,
    }
})

const User = mongoose.model('User',userSchema)

module.exports = User

Solution: The solution is very simple, all I need to do is that turn of the unique key explicitly. either by typing false or deleting it. See the below code that fix my problem:

const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
    email : {
        type : String,
    },
    password : {
        type : String,
    }
})

const User = mongoose.model('User',userSchema)

module.exports = User

You can see that I removed the unique key from the model and the error was solved for me.

Important: This error is created for demo purposes. It is always recommended to use unique email id to prevent multiple accounts with a single email.

If you ever faced this error all you need to do is to check your model carefully and find out that is there any unique key set true by you and if it is not necessary then simply remove the unique key from the model or otherwise set a unique value if it is necessary to be unique. This is how you can fix MongoError**:**e11000 duplicate key error collection.


Share on social media

//