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.

MongoDB remove unique constraint MongoDB remove unique constraint Reviewed by JSDevLife on Wednesday, June 05, 2019 Rating: 5

No comments:

Powered by Blogger.