Skip to content
Advertisement

Mongoose Return Error Code 11000 duplicate index

i am using mongoose as database for my project, now i am struggling with add data to multiple collections and this is my route

router.post('/',add_new_user_to_specific_collection,add_new_user_to_collection_User);

this is code of middleware add_new_user_to_specific_collection:

JavaScript

and this is for add_new_user_to_collection_User:

JavaScript

the input data is totally validated,

fda

and at the first try, it worked perfectly, but when it comes to the second times, i got this Error:

JavaScript

i have researched for a while and look like email was duplicated but i don’t assign any email property from the body of frontend

UPDATE: THIS IS MY SCHEMA

userSchema:

JavaScript

consultantSchema:

JavaScript

thank you so much for help me out, it means a lot to me, i hope you have a good day

Advertisement

Answer

Not tested on my local but from the code it seems that you’re getting an error because you never assign any value to email field for Consultant while it (almost) must be assigned.

To be more precise, the problem (most likely where the fix is needed) is here:

JavaScript

You create on object with various properties (by the way, you duplicated fullname twice) but the email is not set. And if it is not set, you can only save to database once because null value is still acceptable but with the second insertion, you would get an error because null is no longer a unique value.

To solve this, you need to assign a unique value to email field, for example:

JavaScript

If email is not necessarily required/unique, then you would need to update consultantSchema instead and remove unique: trueforemail` field.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement