10

I've got a problem with creating unique indexes using Mongoose / MongoDb and can't get it to work. I'm able to add two documents with the same attribute values when I have set a unique index.

I've tried everything I can think of - restarting (everything) changing the syntax etc.

Code

Addtion >>

This is the method that I'm using to save an entity:

  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 output

 [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

When I checked in MongoHub the indexes don't appear, so they don't look like they have been created.

This is a duplicate of this question, but it doesn't have an answer that works for me.

4

3 回答 3

8

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

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

从 mongo 外壳

于 2012-10-26T02:56:09.610 回答
5

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

于 2011-05-08T19:09:49.103 回答
3

由于您想在您的集合中应用唯一索引,我建议您删除所有重复的文档。这是执行此操作的代码:

在 Mongo shell 客户端中:

db.agencies.ensureIndex({name: 1}, {unique: true, dropDups: true});
db.agencies.ensureIndex({url: 1}, {unique: true, dropDups: true});
于 2013-11-07T09:51:42.517 回答