Can't create second model document with mongoose

Viewed 24

the first document i am creating with this model is good but when creating second document using this model i am getting this error i tried change the _id to id and thats didn't work

const classSchema = new Schema({
  prettyId: {
    type: Number,
  },
  name: {
    type: String,
    required: true,
  },
  students: [
    {
      name: {
        type: String,
      },
      _id: {
        type: Schema.Types.ObjectId,
        ref: "Student",
      },
      prettyId: {
        type: Number,
      },
    },
  ],
  teachers: [ 
    {
      _id: {
        type: Schema.Types.ObjectId,
        ref: "Teacher",
      },
      name: {
        type: String,
      },
      prettyId: {
        type: Number,
      },
    },
  ],
});

classSchema.plugin(AutoIncrement, {
  id: "classId",
  inc_field: "prettyId",
  start_seq: 10000,
  inc_amount: 1,
  disable_hooks: false,
});

the error i am getting is return callback(new error_1.MongoServerError(res.writeErrors[0])); ^

MongoServerError: E11000 duplicate key error collection: school.classes index: teachers.id_1 dup key: { teachers.id: null }
    {
  index: 0,
  code: 11000,
  keyPattern: { 'teachers.id': 1 },
  keyValue: { 'teachers.id': null },
  [Symbol(errorLabels)]: Set(0) {}
}

the controller which i create from it the class

exports.newClass = async (req, res, next) => {
  const { name } = req.body;
  const myClass = new Class({
    name: name,
    teachers: [],
    students: [],
  });
  await myClass.save();
  res.json({ message: "class createad", myClass });
};
1 Answers

It often happens when you have previously used the collection with different parameters. A quick fix would be to delete the collection and try to see if it works.

Related