问题
I have a mongoose schema defined like the following one:
{
Username: {
type: String,
unique: true,
required: true,
},
Password: {
type: String,
required: true,
minlength: 10,
maxlength: 20
}
}
For example after we launch the production build of our app which is running live, if I want to change "unique" to unique: false
for the "Username" how should I do it?
So on my machine when the server is running i created a User with Username and Password, mongo created User for me, now i changed the Unique Option value to unique: false
manually in the code and restarted my server, mongo throws an error saying "E11000 duplicate key error collection: TFM-Dev-Server.admins index: Username_1 dup key: { Username: \"admin\" }"
. But I did change Unique option to false. Only when I drop my database it works. But I can't keep on dropping my production database with User Data for a small change as this. Someone please tell me how to implement the best way.
In my app Schemas change very often in few areas of my app, I want to deal them without stopping & dropping database of my production server.
Thanks
回答1:
Why you are having the error:
The first time you created the schema with unique: true
, mongoose will auto-create a unique index for the field(i.e Username
). When you change it from within your code to unique: false
, the change won't undo what mongoose had done, the unique index would still be in the database. So whenever you try to insert another document with a Username that already exists(even after toggling the unique option to false
), you will get the index duplicate key error.
The solution:
Firstly, you should know that the unique
option is not a way to validate or enforce the Username
field to be unique but rather it's a helper for building MongoDB unique indexes. Source.
If you are using the unique
option for validation, then the right thing to do would be to remove it and implement other logic to ensure the uniqueness of the Username
field. However, if you are deliberate about using the unique
option to auto-create indexes, then you need to drop the unique indexes whenever you toggle the unique
option to false. You can do that with this in the mongo shell:
db.Admin.dropIndex( { "Username" : -1 } )
回答2:
This is because mongoose
has created a unique index automatically when you first define the unique field.
You can drop index via mongodb command:
db.pets.dropIndex( { "cat" : -1 } )
Read more here
or via mongoose
, like this (you need to change this to adapt to your project)
var Driver = mongoose.model('admins', DriverSchema);
// Dropping an Index in MongoDB
Driver.collection.dropIndex('Username', function(err, result) {
if (err) {
console.log('Error in dropping index!', err);
}
});
module.exports = Driver;
来源:https://stackoverflow.com/questions/59599830/mongoose-schema-option-change-doesnt-reflect-in-database