已修改 mongodb 数据库并面临问题

modified mongodb database and facing problems

我正在使用 passport-local-mongoose 在我的网站上实施身份验证,但是在注册新用户时我收到以下错误:

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

我以前有一个用户的电子邮件字段,但我删除了它,因为它对我的应用程序来说不是必需的

这是我的模型

 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);

我也在使用 mongodb atlas 作为我的数据库

第一次注册新用户时没有出现这个错误 我该如何解决这个问题?

您以前的电子邮件字段似乎设置了 unique index

第一个用户创建良好,没有电子邮件,因为没有其他用户设置了 "email": null。既然有一个,所有没有电子邮件的新用户都是重复的,unique 索引不允许重复。

与模式不同,索引是在数据库中设置的,而不仅仅是在代码中设置的。这意味着您将不得不从数据库中删除索引。您可以通过任何 GUI mongodb 浏览器执行此操作。当您使用 Atlas 时,您可以直接通过他们的网络界面进行操作。这是 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.