【问题标题】:"E11000 duplicate key error collection: class index: student.name_1 dup key: { : null }" when insert in related collection“E11000 重复键错误集合:类索引:student.name_1 重复键:{:null }”在相关集合中插入时
【发布时间】:2021-10-10 16:13:57
【问题描述】:

我有以下两个收藏:

const studentSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      index: true,
      required: [true, "Name should be required"],
      unique: [true, "Name should be unique"],
    },
    gender: {
      type: String,
      enum: ["male", "female"],
      required: true,
    },
  }
);

const classSchema = new mongoose.Schema({
  class: {
    type: String,
    index: true,
    trim: true,
    validate: /^$|\S+/,
    required: [true, "Class should be required"],
    unique: [true, "Class should be unique"],
  },
  students: {
    type: [{ type: Schema.ObjectId, ref: STUDENTS_COLLECTION }],
    required: true,
  },
});

这个想法是每个学生应该有一个不同的名字,但每个学生可以在多个班级。

然后我创造一个学生第一

await new Student({name: "A", gender: "male"}).save(); -> objectId 1
await new Student({name: "B", gender: "male"}).save(); -> objectId 1
await new Student({name: "C", gender: "male"}).save(); -> objectId 1

我创建了第一个类:

  new Class({
    class: "Class A",
    students: [1, 2, 3],
  });

问题是当我尝试执行第二个new Class

  new Class({
    class: "Class B",
    students: [1],
  });

得到以下错误:

“E11000重复键错误集合:类索引:students.name_1 dup key:{:null}”

为什么我得到一个错误,如果只有类的名称不同?

谢谢

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    看起来您在 classes.students.name 上有一个唯一索引。这可能是以前版本的代码遗留下来的。请注意,一旦您在代码中声明索引并运行该代码,该索引就会无限期地保存在数据库中,除非您主动删除它。当连接到数据库时,您可以通过在 mongo shell 中运行 db.classes.getIndexes() 来检查索引。

    如果我是正确的并且索引在那里,您可以通过运行 db.classes.dropIndex('students.name_1') 删除索引

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 2019-06-17
      • 2016-08-17
      • 1970-01-01
      • 2021-09-19
      • 2021-03-04
      • 2018-07-29
      • 2019-01-05
      相关资源
      最近更新 更多