唯一索引不适用于Mongoose / MongoDB

我有使用Mongoose / MongoDb创build唯一索引的问题,并不能得到它的工作。 我可以添加具有相同属性值的两个文档,当我设置一个唯一的索引。

我已经尝试了所有我能想到的 – 重新启动(一切)改变语法等

添加>>

这是我用来保存实体的方法:

create : function(entity, definition, successFn, errorFn){ var model = mongoose.model(entity); newModel = new model(definition); newModel.save(function(error) { if(error){ if(!errorFn){ throw error; } errorFn(newModel); return; } successFn(newModel); }); }... 

<<

 var Something = new Schema({ objectId : ObjectId, name : { type : String, index: { unique: true }}, url : { type : String, index: { unique: true }}, ...etc mongoose.model('Something', Something); 

Mongo输出

  [conn1] insert xxxxx.agencies 1526ms [conn1] building new index on { name: 1 } for xxxxx.agencies [conn1] insert xxxxx.system.indexes exception 11000 E11000 duplicate key error index: xxxxx.agencies.$name_1 dup key: { : "something" } 4ms [conn1] building new index on { url: 1 } for xxxxx.agencies [conn1] insert xxxxx.system.indexes exception 11000 E11000 duplicate key error index: xxxxx.agencies.$url_1 dup key: { : "http://www.something.com" } 1ms 

当我在MongoHub中检查索引不会出现,所以他们看起来不像他们已经创build。

这是这个问题的重复,但它没有一个适合我的答案。

一个不涉及删除你的数据库的解决scheme是手动删除任何重复,然后运行一些东西:

 db.users.ensureIndex({email:1},{unique:true,sparse:true}); 

从蒙戈壳

看起来好像索引无法创build,因为MongoDB集合中已经有重复的数据。 如果可能,请尝试删除所有数据,然后重新开始使用空集合。

既然你想在你的collections中应用唯一的索引,我build议你删除任何重复的文档。 这是做这件事的代码:

在Mongo shell客户端中:

 db.agencies.ensureIndex({name: 1}, {unique: true, dropDups: true}); db.agencies.ensureIndex({url: 1}, {unique: true, dropDups: true});