node.js - Mongo DB:更新文档的某些字段以及在一个 FindbyIdandUpdate 中推送参考
问题描述
感谢您帮助我,我是 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 天。
解决方案
Doctor.findByIdAndUpdate(req.params.id,{$set: req.body,$push: { doctorSpecialities: req.body.speciality} }, {new: true}, function (err, doctor) {
if(err){
return res.status(400).send("Error" + err);
}else {
Specialty.findByIdAndUpdate(req.body.speciality,{$push: { specialtiesDoctors: doctor._id}}, {new: true}, function (err, speciality) {
if(!err){
return res.status(200).send({'Success' : true , 'Data' : doctor});
}
});
}
});
推荐阅读
- php - php中的SQL查询,来自html下拉列表的输入
- plugins - ol.featureAnimation.Zoom 和 ol.layer.AnimatedCluster 的 ol4 + ol-ext 问题
- javascript - 数组检查匹配项
- java - 如何从类中的值更新 HashMap 键?
- algorithm - 为什么该算法适用于二次探测?
- c# - 为什么随机数没有正确分散?
- web-scraping - 挣扎于 Scrapy 分页
- java - 如何在app中提取网站的html代码
- javascript - 函数将一行作为字符串附加到表中
- mongodb - 在使用 GORM mongoDB 插件的 Grails 应用程序中配置 MongoDatastore 类的 bean 覆盖的最佳方法是什么?