Updating mongoose subSchema Object

Issue

My Schema is like this

const subSchema = new Schema({ /*...*/ })

const mainSchema = new Schema({
  //...,
  foo:{
    type:subSchema,
    default:{}
  }
})

const Model = model('Model', mainSchema)

If I am doing this the whole foo get replaced by req.body

Model.findByIdAndUpdate(_id,{ foo:req.body }, { new:true,runValidators:true })

But I want that the only fields present in req.body get replaced and the rest remain same

Solution

You can create an variable that contains fields to update from req.body first. Something like:

let update = Object.keys(req.body).reduce((acc, cur) => {
   acc[`foo.${cur}`] = req.body[cur];
   return acc;
}, {});

Model.findByIdAndUpdate(_id, update,...

Answered By – Cuong Le Ngoc

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published