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
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
The indexes in that collection
If any more details is required, please tell in comments.
2
Answers
Try
index:true
or
unique:true
fields from the Schema (rely on different method of validation of duplicate items)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 emptydata
array as that would causedata.email
to beundefined/null
in the second document as well.Setting
data
to beundefined
, rather than[]
should remedy that.As mentioned by vkarpov15 on Sequelize’s issue tracker:
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.