How can I update an array of nested document using NodeJS and mongoose?

Viewed 11

I want to add multiple objects of the nested document called 'procedure' without using $push or addToSet only updating the procedures array

const procedureSchema = Schema({
    intervention: String,
    guide: {type: String, enum: [ 'U', 'F', 'L', 'H' ]},
    procedureDetail: String,
},{timestamps: true
})

this is the main schema

///////////// MAIN SCHEMA /////////////////
const visitSchema = new Schema({
    patientId: {type: mongoose.Types.ObjectId, require: true},
    referredBy: String,
    allergy: [String],
    pmhx: [String],
    pshx:[String],
    cc: String,
    hopi: String,
    procedure: [procedureSchema],
}, { // The timestamps property introduced by MongoDB that will add CreatedAt, and UpdatedAte
    timestamps: true,
});

const VisitModel = model('visits', visitSchema);
module.exports = VisitModel;

// here the client will enter the details of the visit
    updateVisit: async (req, res) => {
        try {
            // the client will send the id of the visit to add details
            const { id } = req.params;
            const { cc, hopi, pmhx, allergy, intervention, guide, procedureDetail } = req.body

here the find and update method

            const updateVisit = await VisitModel.findOneAndUpdate({_id: id}, {
                cc,
                hopi,
                // this MongoDB property used to add new thing to the 
                $set: {
                    // Don't put []
                    allergy: allergy,
                    pmhx: pmhx,

here the nested that I want to updated it

                    procedure: [
                        { intervention: intervention, guide: guide, procedureDetail: procedureDetail },
                    ],
                },
            }, 
            // this mean if you didn't find this visit id add new
            { upsert: true });
            updateVisit.save();
            res.send(`${id} visit was successfully updated`)
        } catch (error) {
            res.send(error)
        };
    },
0 Answers
Related