Reputation: 360
Hiii, I have a MEAN stack application that make use of a mongoose model defined as below:
appointment.js
var mongoose = require('mongoose');
module.exports = mongoose.model('Appointment', {
appt_date: String,
details: [ {
appt_time: String,
patient_id : String,
patient_name : String,
contact_no: String,
doctor_name : String,
purpose : String
}
]
});
I want to generate a document like the following:
{
appt_date: 13/13/2013,
details: [
{
appt_time: 09:00 AM,
patient_id: 2015/2016,
patient_name: David John,
contact_no: 8965741234,
doctor_name: Albert ,
purpose: Consultation,
}
}
I can't generate a document when using the following Express JS code:
var Appointment = require('../../models/appointment');
var appointments = new Appointment ({ "appt_date" : req.body.date});
appointments.save();
Appointment.update({ appt_date: req.body.date},
{
$push: {
'details': {
appt_time:"09:00 AM",
patient_id:"2015/2016",
patient_name:"Wilfred",
contact_no:"8965741234",
doctor_name: "Albert",
purpose: "Consultation"
}
}
},
{
upsert:true
});
After performing the above operations, the result that I get is as follows:
"_id": ObjectId('57b6eefd2b494e802ba146d8'),
"appt_date": "12/20/2014",
"details": [],
"__v": 0
I am not able to push any data to the "details" array. What I am in need is a single date entry (appt_date), multiple details (details array). Please help to solve this out.
Thank You.
Upvotes: 3
Views: 863
Reputation: 2014
You are updating document against the date and might be there are more than 1 app_date, this scenario will update multiple document ., you have to add multi : true object
Appointment.update({ appt_date: req.body.date},
{
$push: {
'details': {
appt_time:"09:00 AM",
patient_id:"2015/2016",
patient_name:"Wilfred",
contact_no:"8965741234",
doctor_name: "Albert",
purpose: "Consultation"
}
}
},
{multi: true},
{
upsert:true
});
or you can update it by _id
Upvotes: 0
Reputation: 2923
Try with this code:
var Appointment = require('../../models/appointment');
var appointments = new Appointment();
appointments.appt_date = req.body.date;
appointment.details.push({appt_time:"09:00 AM",patient_id:"2015/2016", patient_name:"Wilfred",contact_no:"8965741234",doctor_name: "Albert",
purpose: "Consultation"});
appointments.save(function(err){
if(!err)
console.log("saved")
})
Upvotes: 0
Reputation: 103305
No need to do an update after save()
, just use the push()
method on the details
key and then save. For example:
var Appointment = require('../../models/appointment');
var appointments = new Appointment ({ "appt_date" : req.body.date});
appointments.details.push({
appt_time: "09:00 AM",
patient_id: "2015/2016",
patient_name: "Wilfred",
contact_no: "8965741234",
doctor_name: "Albert",
purpose: "Consultation"
});
appointments.save(function(err, appointment){
if (err) handleErr(err);
console.log(appointment);
});
Upvotes: 1