mongodbexpressmongoosemongoose-schemasubdocument

Updating mongoose subSchema Object


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,...