skip to Main Content

This is the code I am writing:

      const createOrgPerso= new Person({
        org: newOrganisation._doc.id,
        // data: [],
      });

But the empty array is still getting created. And then this code is run again, it gives E 11000 duplicate key error collection: managerhq.studentdatas index: data.email_l dup key: { data.email: null } error

enter image description here

Problem description :

I think this is because I have set required: true for some fields.

What I want is:

Just create a document with the org field only. I will fill the data array with documents later.
My goal is: same email(also few other fields) cannot be repeated in the data array

This is the mongoose schema

enter image description here

The indexes in that collection
enter image description here

If any more details is required, please tell in comments.

2

Answers


  1. Try

    1. removing the index:true
      or
    2. removing the unique:true fields from the Schema (rely on different method of validation of duplicate items)
    Login or Signup to reply.
  2. Your ORM, Mongoose, creates an empty array when you save a new instance. Mongo considers undefined/null a unique value so you can’t have two instances that have an empty data array as that would cause data.email to be undefined/null in the second document as well.

    Setting data to be undefined, rather than [] should remedy that.

    As mentioned by vkarpov15 on Sequelize’s issue tracker:

    If you have an array in your schema, mongoose will create an empty array [] for you by default so you can do .push() and such without explicitly creating the array. To shut this off, overwrite the default array default

    var schema = new Schema({
     myArr: { type: [String], default: undefined }
    });
    

    As you posted your code as an image and not text you can integrate the above solution into your code yourself, as I’m not going to transcribe it. Be mindful of people trying to help you as the guidelines on how to ask questions aren’t for fun but proper manners.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search