how to update nested object of mongoose document for only provided keys how to update nested object of mongoose document for only provided keys mongoose mongoose

how to update nested object of mongoose document for only provided keys


When nested object has more complex hierarchy, how can we solve this without manually indicate field like address.city.field1.field2.

As most answers intimated, you have to use the dot notation to update embedded documents and to answer your above question, use the following helper method which applies recursion to convert a given object to its dot notation representation:

function convertToDotNotation(obj, newObj={}, prefix="") {  for(let key in obj) {      if (typeof obj[key] === "object") {          convertToDotNotation(obj[key], newObj, prefix + key + ".");      } else {          newObj[prefix + key] = obj[key];      }  }  return newObj;}let params = {   address: {      city: {         location: {            street: "new street"         }      }     }};const dotNotated = convertToDotNotation(params);console.log(JSON.stringify(dotNotated, null, 4));