Home > Blockchain >  modified mongodb database and facing problems
modified mongodb database and facing problems

Time:03-15

I am implementing authentication in my website using passport-local-mongoose but when registering new users I receive the following error:

MongoServerError: E11000 duplicate key error collection: myDatabase.users index: email_1 dup key: { email: null }

I previously had an email field for my user but I deleted it because it was not necessary for my application

here is my model

 var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
  
  
var UserSchema = new Schema({
    username : {type: String, unique: true, required: true},
});
  

UserSchema.plugin(passportLocalMongoose);
  

 module.exports = mongoose.model("User", UserSchema);

I am also using mongodb atlas as my database

This error didn't show up the first time I registered a new user How can I fix this problem?

CodePudding user response:

It looks like the email field you used to have had a unique index set on it.

The first user got created fine with no email as there were no other users with "email": null set on them. Now that there is one, all new users without email will be duplicates, and a unique index does not allow duplicates.

Indexes, unlike schemas, are set on the database and not just in code. This means you will have to delete the index from your database. You can do this via any GUI mongodb browser. As you are using Atlas, you can do it directly via their web interface. Here are the instructions:

Drop an Index

To drop an index from a collection through the Data Explorer:

1 Go to the Indexes tab.

Select the collection whose index you wish to drop, and go to the Indexes tab.

2 Click the Drop Index button for the index to drop.

3 Confirm action.

Confirm by typing the name of the index, and click Drop.

  • Related