如何只为提供的键更新猫鼬文档的嵌套对象 [英] how to update nested object of mongoose document for only provided keys

查看:33
本文介绍了如何只为提供的键更新猫鼬文档的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将根据提供的键更新 mongoose 文档的某些字段.例如,当我们在 json 中呈现 mongoose 文档时.

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"
}

当我像这样运行 mongoose api 时.

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?

当嵌套对象具有更复杂的层次结构时,我们如何在不手动指示字段(如address.city.field1.field2)的情况下解决此问题....

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 这样的字段.

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

这篇关于如何只为提供的键更新猫鼬文档的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆