将新记录添加到嵌套数组中

时间:2017-08-18 17:58:45

标签: javascript node.js mongodb mongoose

我无法在医生阵列名称下添加新的医生信息 :使用Mongoose在我的mongodb中进行IVF

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

             }] },
    ],

我使用以下代码添加新的医生信息

 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) {})

而不是添加新的医生记录名称:' Root Canal'进入医生阵列,它在治疗阵列下创建新对象。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

使用positional $ operator,以下应该可以解决问题:

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) {})