Search code examples
node.jsmongodbmongoosemongoose-schema

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


I have the following two collections:

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

The idea is that each student should have a different name, but each student could be in more than one class.

Then I create a firsts students

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

and I create the the first class:

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

The problem is that when I try to execute the second one new Class

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

Got the following error:

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

Why I am getting an error that if only the name of the class is different?

Thanks


Solution

  • Looks like somehow you have a unique index on classes.students.name. Possibly this was left over from a previous revision of code. Note that once you declare an index in code and run that code, the index is saved in the database indefinitely unless you actively remove it. You can check your indexes by running db.classes.getIndexes() in your mongo shell when connected to your database.

    If I'm correct and the index is there, you can remove the index by running db.classes.dropIndex('students.name_1')