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:

var newConsultant = new Consultant({
  fullname,
  _id: new mongoose.Types.ObjectId(),
  fullname,
  code,
  vnumail: code.trim() + '@vnu.edu.vn',
  ...newUserData,
});

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:

var newConsultant = new Consultant({
  fullname,
  _id: new mongoose.Types.ObjectId(),
  email: <some_random_and_unique_email>,
  code,
  vnumail: code.trim() + '@vnu.edu.vn',
  ...newUserData,
});

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top