【发布时间】:2020-06-25 20:05:12
【问题描述】:
感谢您的帮助,我是 Mongo DB 的新手,我正在通过引用实现多对多关系。
注意:我知道如何在不同的通话中执行此操作,我想在一次通话中使用最佳做法进行更新
用例:医生和专科(多对多)。
当医生更新时,例如在他的个人资料中添加专业,也会更新一些个人信息,例如电话、州城。
必填 它的引用数组需要与它的字段一起更新。 此外,专业数组需要由医生更新为专业参考数组。
医生架构
const doctorSchema = new Schema({
_id : mongoose.Schema.Types.ObjectId,
email : {
type : String,
required : true,
unique : true,
lowercase: true,
validate: value => {
if (!validator.isEmail(value)) {
throw new Error({error: 'Invalid Email address'})
}
}
},
Name : {
type : String
},
password : {
type : String,
required : true,
minLength : 7
},
gender : {
type : String
},
address : {
type : String
},
state : {
type : String
},
city : {
type : String
},
zip : {
type : Number
},
phone : {
type : Number,
required : true,
unique : true
}doctorSpecialities : [{
type : Schema.Types.ObjectId,
ref : "Specialty"
}]};
专业架构
const specialtySchema = new Schema({
_id : mongoose.Schema.Types.ObjectId,
name :{
type : String
},
specialtiesDoctors : [{
type : Schema.Types.ObjectId,
ref : 'Doctor'
}]
});
module.exports = mongoose.model('Specialty', specialSchema);
医生更新个人资料电话
updateDoctorInfo : async (req, res) => {
/** mongoose _id validation */
if(!mongoose.isValidObjectId(req.params.id)){
return res.status(400).json({
"Success" : false,
"Message" : 'Doctor Id wrong format'
})
}
/** mongoose _id Speciality Validation */
if(!mongoose.isValidObjectId(req.body.speciality)){
return res.status(400).json({
"Success" : false,
"Message" : 'Speciality Id wrong format'
})
}
/** updating Doctor's Profile */
let doctor = {};
doctor.username = req.body.username,
doctor.phone = Date.parse(req.body.DOB),
doctor.gender = req.body.gender,
doctor.address = req.body.address,
doctor.state = req.body.state,
doctor.city = req.body.city,
doctor.zip = Number(req.body.zip),
doctor.speciality = req.body.speciality,
Doctor.findByIdAndUpdate(req.params.id, doctor, {new: true}, function (err, doctor) {
if (err){
return res.status(500).send("There was a problem updating the user.");
}
return res.status(200).send(doctor);
});
},
我只想在这次通话中更新专业中的参考数组和医生。
请帮助我被困了将近 2 天。
【问题讨论】:
标签: node.js mongodb mongoose many-to-many updates