Sona Shetty Sona Shetty - 1 month ago 19
Node.js Question

Adding new record into nested array

I am unable to add new doctor information under doctor array where name
:IVF in my mongodb using Mongoose

hospitalID: 10001,
hospitalName: 'Renai MediCity',
__v: 0,
updated_at: 2017-08-18T17:34:53.784Z,
Treatment:
[ { name: 'Root Canal',
costUpperBound: 10000,
costLowerBound: 8000,
departmentId: 10001,
procedureid: 10001,
departmentName: 'Dental',
_id: 599725530c126c1efc43dc52,
doctor:[ {
profilepicdir:"smdir1",
doctorName:"Dr.vp2",
doctorId:10002,_id:5997255c0c126c1efc43dc57

}] },
],


I am using the below code code for adding a new doctor information

hospitalModel.findOneAndUpdate({
"hospitalName": hospitalName, "hospitalContact.City": hospitalCity, "hospitalContact.country": hospitalCountry, "Treatment": {
$elemMatch: { "name": procedureName }
}},
{
"$push": {
"Treatment": {
"doctor": {
"doctorId": doctorID,
"doctorName": req.body["doctorName"],
"profilepicdir": req.body["profilePicDirectory"],
"medinovitadoctorRating": parseInt(req.body["medinovitaDoctorRating"]),
"speciality": {
"specialityName": req.body["specialityName"]
}
}
}
}
},
{ returnOriginal: false, upsert: true }, function (err, doc) {})


Instead of adding new doctor record where name: 'Root Canal' into doctor array,its creating new object under treatment array.

Can some one help me to resolve this?

Answer Source

Using the positional $ operator, the following should do the trick:

hospitalModel.findOneAndUpdate({
                "hospitalName": hospitalName, "hospitalContact.City": hospitalCity, "hospitalContact.country": hospitalCountry, "Treatment": {
                    $elemMatch: { "name": procedureName }
                }},
                {
                    "$push": {
                        "Treatment.$.doctor": {
                            "doctorId": doctorID,
                            "doctorName": req.body["doctorName"],
                            "profilepicdir": req.body["profilePicDirectory"],
                            "medinovitadoctorRating": parseInt(req.body["medinovitaDoctorRating"]),
                            "speciality": {
                                "specialityName": req.body["specialityName"]
                            }
                        }
                    }
                },
                { returnOriginal: false, upsert: true }, function (err, doc) {})