唯一索引不适用于Mongoose / MongoDB [英] Unique index not working with Mongoose / MongoDB

查看:94
本文介绍了唯一索引不适用于Mongoose / MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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输出



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

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

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.

推荐答案

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

one solution that doesn't involve erasing your db, is to remove any duplicates manually, then run something along the lines of:

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

这篇关于唯一索引不适用于Mongoose / MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆