我正在尝试使用“ $ push”功能将多个元素输入到mongodb数组中。使用下面的代码,我可以将单个元素添加到数组,但是当我尝试将多个元素添加到数组时,仅添加对象ID,而不会传递。我已经尝试使用POSTMAN尝试许多JSON请求格式,但是似乎都没有用。请帮助我理解问题。
快速路线:
// @route PUT api/prescription/:patientId
// @desc Add prescription
// @access Private
router.post('/:patientId',auth,adminDocguard, async(req,res)=>{
const {
mediaction,
dosage,
morning,
evening
}=req.body;
var newPrescription={
mediaction,
dosage,
morning,
evening
}
console.log(newPrescription)
try {
const patient_profile = await Patient.findOneAndUpdate(
{patientId:req.params.patientId},
{"$push":{"prescription":newPrescription}},
{"upsert":true,"new":true}
);
//patient_profile.prescription.unshift(newPrescription);
await patient_profile.save();
res.json(patient_profile);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
module.exports=router;
Mongo模式
const mongoose= require('mongoose');
autoIncrement = require('mongoose-auto-increment');
const config =require('config');
const db=config.get('mongoURI');
var connection = mongoose.createConnection(db);
autoIncrement.initialize(connection);
const PatientSchema = new mongoose.Schema({
name:{
type:String,
required: true
},
phonenumber:{
type:Number,
required:true
},
date: {
type: Date,
default: Date.now
},
slider_1:{
type:Number,
required: true
},
slider_2:{
type:Number,
required:true
},
slider_3:{
type:Number,
required:true
},
prescription:[
{
mediaction:{
type:String
},
dosage:{
type:Number
},
morning:{
type:Number
},
evening:{
type:Number
}
}
]
});
PatientSchema.plugin(autoIncrement.plugin, {
model:'Patient',
field:'patientId',
startAt:1,
incrementBy:1
});
module.exports=Patient=mongoose.model('patient',PatientSchema);
Json请求
{
"prescription": [
{
"mediaction": "Crocin123",
"dosage": 200
},
{
"mediaction": "Crocin456",
"dosage": 200
}
]
}