简体   繁体   English

如何仅为提供的密钥更新mongoose文档的嵌套对象

[英]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. 我将根据提供的密钥更新mongoose文档的某些字段。 For example, When we present mongoose document in json. 例如,当我们在json中呈现mongoose文档时。

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

And update params is given like this. 更新params就是这样给出的。

address: {
   city: "city_new"
}

when I run the mongoose api like this. 当我像这样运行mongoose api时。

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. ... 当嵌套对象具有更复杂的层次结构时,如何在不手动指示address.city.field1.field2. ...字段的情况下解决此问题address.city.field1.field2. ... address.city.field1.field2. ...

Thanks 谢谢

When nested object has more complex hierarchy, how can we solve this without manually indicate field like address.city.field1.field2. 当嵌套对象具有更复杂的层次结构时,如何在不手动指示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)); 

This should work: 这应该工作:

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

In the documentation on $set you'll also find the following remark: $ set的文档中,您还会找到以下注释:

To specify a <field> in an embedded document or in an array, use dot notation. 要在嵌入文档或数组中指定<field>,请使用点表示法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM