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
:
exports.add_new_user_to_specific_collection = (req, res, next) => { const {role, fullname, code} = req.body; const generator = new AvatarGenerator(); // it generate random image, no worry const hashedPassword = bcrypt.hashSync(code.toString(), 10); console.log(hashedPassword); const newUserData = { password: hashedPassword, profileImage: generator.generateRandomAvatar(), }; if (role === 'consultant') { var newConsultant = new Consultant({ fullname, _id: new mongoose.Types.ObjectId(), fullname, code, vnumail: code.trim() + '@vnu.edu.vn', ...newUserData, }); newConsultant .save() .then((doc) => { console.log('New User as Consultant was added'); req.newUserData = newUserData; next(); }) .catch((err) => { res.status(500).json({err}); }); } };
and this is for add_new_user_to_collection_User
:
exports.add_new_user_to_collection_User = (req, res, next) => { const {role, fullname, code} = req.body; const newUser = new User({ _id: new mongoose.Types.ObjectId(), role, fullname, code, vnumail: code.trim() + '@vnu.edu.vn', ...req.newUserData, }); newUser .save() .then((doc) => { console.log('New User added to collection User'); return res.status(200).json({ message: 'User added', doc, }); }) .catch((error) => { console.log(error); res.status(500).json(error); }); };
the input data is totally validated,
and at the first try, it worked perfectly, but when it comes to the second times, i got this Error:
{ "err.driver": true, "err.name": "MongoError", "err.index": 0, "err.code": 11000, "err.keyPattern.email": 1, "err.keyValue.email": null }
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
:
const mongoose = require('mongoose'); const userSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, code: { type: String, required: true, unique: true, }, fullname: { type: String, required: true, }, password: { type: String, required: true, }, activated: { type: Boolean, }, vnumail: { type: String, required: true, unique: true, match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/, }, profileImage: { type: String, default: 'https://kittyinpink.co.uk/wp-content/uploads/2016/12/facebook-default-photo-male_1-1.jpg', }, role: { type: String, required: true, enum: [ 'consultant', 'parent', 'student', 'specialist', 'uet-leader', 'student-affair-leader', 'academic-leader', ], default: 'student', }, }); const User = mongoose.model('User', userSchema); module.exports = User;
consultantSchema
:
const mongoose = require('mongoose'); const consultantSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, fullname: { type: String, required: true, }, code: { type: String, required: true, }, gender: { type: String, required: true, enum: ['Male', 'Female', 'No Record'], default: 'No Record', }, birthday: { type: Date, }, email: { type: String, unique: true, match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/, }, vnumail: { type: String, required: true, unique: true, match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/, }, profileImage: { type: String, }, address: { type: String, }, academicRank: { type: String, required: true, enum: ['master', 'phd', 'professor'], default: 'master', }, specialize: { type: String, }, }); const Consultant = mongoose.model('Consultant', consultantSchema); module.exports = Consultant;
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:
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: truefor
email` field.