"E11000 duplicate key error collection: class index: student.name_1 dup key: { : null }" 插入相关集合时

"E11000 duplicate key error collection: class index: student.name_1 dup key: { : null }" when insert in related collection

我有以下两个合集:

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,
  },
});

想法是每个学生应该有不同的名字,但每个学生可以在多个 class.

那我创个第一的学生

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

我创建了第一个 class:

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

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

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

出现以下错误:

"E11000 duplicate key error collection: class index: students.name_1 dup key: { : null }"

如果 class 的名称不同,为什么我会收到错误消息?

谢谢

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

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

删除索引