即使唯一的约束不存在,mongoose唯一的validation错误

var schema = new Schema({ _id: Schema.ObjectId, email: {type: String, required: true} }); 

以前的email字段是唯一的(具有唯一的约束)现在我删除了唯一的约束,然后它也给出了唯一的validation错误。 我已经重新启动了mongo,然后也是抛出错误。 任何想法?

当您在模式定义中删除唯一约束时,您应该手动从数据库中删除它。 您可以使用dropIndex()方法在mongo shell中执行此操作,也可以在使用dropIndex()的本机node.js驱动程序的dropIndex()方法的应用程序中执行此操作。

您可能需要首先确认数据库中当前的索引, 在Mongoose中定义模式之后,最有可能find在填充集合时创build的电子邮件唯一索引。

您可以在mongo shell中发出命令,假设您的数据库中有名为test users名为test的集合:

 > db.users.getIndexes() 

这将显示当前的索引,你可以在你的控制台看到如下所示的数组:

 [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.users" }, { "v" : 1, "unique" : true, "key" : { "email" : 1 }, "name" : "email_1", "ns" : "test.users", "background" : true, "safe" : null } ] 

对于应用程序代码中的解决scheme,假设您有一个名为User具有上面定义的模式的Mongoose模型,则可以调用getIndexes()本机node.js驱动程序的收集方法:

 User.collection.getIndexes(function (err, results) { // Handle errors }); 

在mongo shell中,您可以继续使用dropIndex()方法删除电子邮件索引:

 > db.users.dropIndex("email_1") 

在您的应用程序代码中,您还可以通过集合的Mongoose模型发出命令,并调用集合的本地node.js驱动程序的dropIndex()方法:

 User.collection.dropIndex("email_1", function (err, results) { // Handle errors });