【问题标题】:Mongo not allowing save to duplicate data, even after specifying as not uniqueMongo 不允许保存重复数据,即使在指定为不唯一之后也是如此
【发布时间】:2020-05-17 13:43:32
【问题描述】:

我已将 firstname 和 lastname MongoDB 字段指定为 不 是唯一的,但我仍然遇到一个问题,我不能说非唯一的名字和姓氏。

如何向 MongoDB 指定 firstname 和 lastname 的重复项是可以的?

extend type Mutation {
    signUp(
      firstname: String!
      lastname: String!
      email: String!
      password: String!
    ): Token!

...

const userSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      unique: true,
      required: true,
      validate: [isEmail, 'Not a valid email'],
    },
    firstname: {
      type: String,
      unique: false
    },
    lastname: {
      type: String,
      unique: false
    },
    password: {
      type: String,
      required: true,
      minlength: 7,
      maxlength: 42,
    },
  },
  {
    timestamps: true,
  },
);

错误:

E11000 duplicate key error collection: testDb.users index: firstname_1 dup key: { firstname: "Test" }

【问题讨论】:

  • 您需要删除users 集合并运行您的应用程序。似乎您已经创建了唯一索引,现在您正在尝试撤消它
  • 我不确定您是如何发现的(或者我会如何发现),但这确实有效。我放弃了我的 testDB 并且一切正常..奇怪

标签: mongodb mongoose


【解决方案1】:

由于您已经在集合上创建了唯一索引,如 firstname_1 dup key: { firstname: "Test" } 所说,那么您需要先删除它,然后再插入重复的文档。通常,您会在 mongoose 模式中的字段上提及 unique:true,以便第一次从代码创建唯一索引,而不是手动执行 DB 命令,无论如何实际上是在数据库上创建索引。因此更改代码不会删除数据库上的现有索引。要么你必须在 DB 上手动运行dropIndex,要么通过猫鼬试试这个drop-indexes-using-mongoose:

db.users.dropIndex( "firstname_1" )

【讨论】:

    【解决方案2】:

    unique: false 不会强制 mongoose 删除您的特定索引。由于您已经在数据库中创建了索引,因此您应该使用 mongo shell 手动或以编程方式删除它们。

    在 mongo shell 中它看起来像

    db.users.dropIndex('firstname_1');
    db.users.dropIndex('lastname_1');
    

    但在此之前最好仔细检查精确的索引名称,为此我们有以下命令

    db.users.getIndexes();
    

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 2017-08-03
      • 2015-05-18
      • 1970-01-01
      • 2021-10-22
      相关资源
      最近更新 更多