在这个应用程序中,我有3个型号PS,ENG和病人 在创建/更新PS或ENG
时,我需要在特定字段中填充和更新患者ENG模型
'use strict';
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const ENGSchema = new Schema({
eng_name: {
type: String,
required: [true, 'Kindly enter the name of the ENG']
},
...
eng_ur: String,//This is Patient number
eng_inout: {
type: String,
enum: ['Inpatient', 'Outpatient'],
ref: 'Patient'
},
eng_inout_date: { type: Date, ref: 'Patient' },
eng_inout_loc: { type: String, ref: 'Patient' },
eng_inout_reason: { type: String, ref: 'Patient' },
...
module.exports = mongoose.model('ENGs', ENGSchema);
患者模型
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PatientSchema = new Schema({
...
patient_status: {type: Schema.Types.ObjectId, ref: 'ENGs'||'PSs'},
patient_inout_date: {type: Schema.Types.ObjectId, ref: 'ENGs'||'PSs'},
patient_inout_loc: {type: Schema.Types.ObjectId, ref: 'ENGs'||'PSs'},
patient_inout_reason: {type: Schema.Types.ObjectId, ref: 'ENGs'||'PSs'},
...
module.exports = mongoose.model('Patients', PatientSchema);
据我了解,我需要为PS和ENG模型创建一个中间件,如pre('save')
,或者我可以在我的控制器中完成。
ENG控制器
'use strict';
const mongoose = require('mongoose'),
ENG = mongoose.model('ENGs'),
Patient = mongoose.model('Patients'),...;
exports.create_eng = (req, res)=> {
let token = getToken(req.headers);
if(token){
req.body._user = checkPermissionReturnUserName(token);
let new_eng = new ENG(req.body);
new_eng.save((err, eng)=> {
if (err) res.send(err);
else{
res.json(eng);
//Something wrong here?
Patient.findOne({patient_ur: this.eng_ur})
.populate({select: 'patient_inout_loc', path: new_eng.eng_inout_loc})
.exec(function (err, patient) {
console.log(patient.patient_inout_loc) //undefined
})
//tried this
Patient.findOne({patient_ur: new_eng.eng_ur})
.populate({path:'patient_inout_loc', select:'eng_inout_loc', model: ENG})
.exec( (err, patient)=> {
if (err) res.send(err);
else res.json(patient);
});
//
}
});
} else return res.status(403).send({success: false, msg: 'Unauthorized.'});
};
这里有什么问题?
我可以这样做(需要能够从PS或ENG填充吗?
patient_inout_loc: {type: Schema.Types.ObjectId, ref: 'ENGs'||'PSs'}
无法从mongoose文档中获取它。有什么建议吗?