JavaScript Solutions, Competitive programming in JavaScript, MCQ in JS

Wednesday, 5 June 2019

MongoDB remove unique constraint

MongoDB Remove the unique constraint:


Src:https://en.wikipedia.org/wiki/MongoDB

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:
POST: 
{ username: 'vikaskad',  email: 'testmail@test.com',  name: 'Vikas Kad' }
{ [MongoError: E11000 duplicate key error index: ecomm_database.users.$email_1  dup key: { : "testmail@test.com" }]  name: 'MongoError',
  err: 'E11000 duplicate key error index: ecomm_database.users.$email_1  dup key: { : "testmail@test.com" }',
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: Date.now } });

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.


3 comments:

  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.

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

      Delete