Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

update nested Object data without changing Object Id


I am currently using array filters to update the nested object. My structure is -

Category Collection - 
{
  name:Disease,
  _id:ObjectId,
  subCategory:[{
    name:Hair Problems,
    _id:ObjectId,
    subSubCategory:[{
       name: Hair Fall,
       _id:ObjectId
    },{
       name: Dandruff,
       _id:ObjectId
    }]
  }]
}

I want to update the subsubcategory with id 1.1.1 which I am doing by using array filters.

let query = { 'subCategories.subSubCategories._id': subSubId };
let update = { $set: { 'subCategories.$.subSubCategories.$[j]': data } };
let option = { arrayFilters: [{ 'j._id': subSubId }], new: true };

await Categories.findOneAndUpdate(query, update, option

This code is working fine but array filters change the object id of subsubCategory. Is there any other alternative to do so without changing the ObjectId.

Thanks in advance


Solution

  • You can loop over the keys which you are getting as payload and put inside the $set operator.

    const data = {
      firstKey: "key",
      secondKey: "key2",
      thirdKey: "key3"
    }
    const object = {}
    
    for (var key in data) {
      object[`subCategories.$.subSubCategories.$[j].${key}`] = data[key]
    }
    
    let query = { 'subCategories.subSubCategories._id': subSubId };
    let update = { '$set': object };
    let option = { 'arrayFilters': [{ 'j._id': subSubId }], 'new': true };
    
    await Categories.findOneAndUpdate(query, update, option)