JavaScript Solutions, Competitive programming in JavaScript, MCQ in JS

Wednesday, 5 June 2019

MongoDB remove unique constraint

MongoDB Remove the unique constraint:


Today, I'm working on a RESTful API Using Node.js With Express and Mongoose example, and I ran into a problem with the MongoDB Schema:
{ username: 'vikaskad',  email: '',  name: 'Vikas Kad' }
{ [MongoError: E11000 duplicate key error index: ecomm_database.users.$email_1  dup key: { : "" }]  name: 'MongoError',
  err: 'E11000 duplicate key error index: ecomm_database.users.$email_1  dup key: { : "" }',
and my schema is as follows:

var Product = new Schema({  
    username: { type: String, required: true },  
    email: { type: String,unique:true, required: true },  
    name: { type: String },  
    createdAt: { type: Date, default: } });

but after some database insertion requirement was like that same mail id can be used by multiple users.
So my question was how do I get rid off MongoDB unique key constraint? When I remove unique: true and restart the app, the schema doesn't get updated.
So I did some research and come with the following solution which worked great with my code.

MongoDB remove the unique constraint

 MongoDB is schema-less so the only thing uniqueness is enforced is on the indexing level where you can define indexes on a collection with unique criteria. So you may want to remove the related index and re-created it if necessary.
To do this I used the following commands:
> use ecomm_database
switched to db ecomm_database
> db.users.dropIndexes();
 "nIndexesWas" : 1,
 "msg" : "non-_id indexes dropped for collection",
 "ok" : 1

so this fixed my issue.
Please comment here, if you know if there any other better solution.


  1. Thanks a lot for this. For a long time I believed that once you created a field with 'unique : true' you couldn't change it. This really saved me a lot of pain!

    Thanks once again.

    1. Glad that it helped you, keep reading other posts as well.

  2. Whether you employ Android, Windows, or iOS cell gadgets, you'll be able to|you'll|you can} dive straight into the catalogue in instant-play mode with no additional software required. Still, the cell compatibility might use some additional work. You’ve filled up at the buffet and you’re itching to roll the cube and see if lady luck is on your aspect. You may have big dreams of hitting the jackpot and retiring on your own private island, 카지노사이트 however that’s not going to happen right here. Gambling is a good time and may supply a pleasant rush when issues shake out in your favor, however it’s not the way it} looks within the movies.