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

I am going to update some fields of mongoose document according to provided keys.
For example,
When we present mongoose document in json.

user: {
  address: {
    city: "city"
    country: "country"
  }
}

And update params is given like this.

address: {
   city: "city_new"
}

when I run the mongoose api like this.

let params = {
   address: {
      city: "city_new"
   }
}
User.set(param)

It replace whole address object and final result is

user: {
  address: {
    city: "city_new"
  }
}

it just replace address field, but I want to only update city field.
This is desired result.

user: {
  address: {
    city: "city_new"
    country: "country"
  }
}

How to do this in mongoose?

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

Thanks

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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));

Solution 2

This should work:

let params = {
   "address.city": "city_new"
}
User.set(param)

In the documentation on $set you’ll also find the following remark:

To specify a <field> in an embedded document or in an array, use dot
notation.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply