唯一索引不适用于Mongoose/MongoDB

Lew*_*wis 9 javascript mongoose mongodb node.js

我使用Mongoose/MongoDb创建唯一索引时遇到问题,无法使其工作.在设置唯一索引时,我可以添加两个具有相同属性值的文档.

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

添加>>

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

  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);
    });
  }...
Run Code Online (Sandbox Code Playgroud)

<<

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

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
Run Code Online (Sandbox Code Playgroud)

当我在MongoHub中检查时,索引没有出现,所以看起来它们看起来并没有被创建.

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

小智 8

一个不涉及擦除数据库的解决方案是手动删除任何重复项,然后按以下方式运行:

db.users.ensureIndex({email:1},{unique:true,sparse:true});
Run Code Online (Sandbox Code Playgroud)

来自mongo shell


Mik*_*ott 5

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