【问题标题】:Unique index not working with Mongoose / MongoDB唯一索引不适用于 Mongoose / MongoDB
【发布时间】:2011-08-21 05:33:06
【问题描述】:

我在使用 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);
    });
  }...

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 时,索引没有出现,所以它们看起来不像是创建的。

这是this question 的副本,但它没有适合我的答案。

【问题讨论】:

    标签: javascript mongodb node.js mongoose


    【解决方案1】:

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

    【讨论】:

    • 谢谢 Mike - 我已经试过了。您看到的输出实际上是在一个全新的数据库之后。虽然你的观点实际上可能让我认为我使用 Mongoose 是错误的。
    • /* Necroposting */ node-mongodb-native的解决方案github.com/christkv/node-mongodb-native/issues/162
    【解决方案2】:

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

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

    来自 mongo 外壳

    【讨论】:

      【解决方案3】:

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

      在 Mongo shell 客户端中:

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

      【讨论】:

        猜你喜欢
        • 2016-11-19
        • 1970-01-01
        • 2018-01-06
        • 2017-05-27
        • 2014-07-01
        • 1970-01-01
        • 2015-03-11
        • 1970-01-01
        • 2012-06-25
        相关资源
        最近更新 更多