繁体   English   中英

如何在Mongoose中更新嵌套字段对象而不动态更新整个对象?

[英]How to update nested field object without updating whole object dynamically in Mongoose?

var userSchema = new Schema({
name: { type: String, default: null },
contacts: {
  mobileNumber: {
    countryCode: { type: String, default: null },
    digits: { type: String, default: null }
  },
  email: { type: String, default: null },
  facebook: { type: String, default: null },
  googlePlus: { type: String, default: null },
  twitter: { type: String, default: null },
  linkedin: { type: String, default: null }
}}, { timestamps: true });

我只想更新此架构的特定嵌套字段。 为此,我要做的是

 updateUser: function (userId, patchObject) {
  var conditions = { "_id": userId };
  User.update(conditions,{$set:patchObject});
}

但是问题是,如果patchObject是{contacts:{email:“ abc@aaa.com”}},它会正确更新电子邮件,但会替换整个联系人对象,在该对象中,我会释放其他字段的所有预定义值。 (例如:facebook)

Google的建议是,

User.update(conditions,{"contacts.email":"abc@aaa.com"});

但是问题是我需要一种动态的方法来对任何类型的对象执行此操作。 我无法对所有可能的值进行硬编码。 有什么方法可以动态更新嵌套字段而无需替换其他内容?

恕我直言,在猫鼬中进行此类更新的最佳和最简便的方法是使用save()方法。 它使您可以将mongodb记录作为纯JavaScript对象处理,因此在我的节点网站上,我尝试:

    User.findOne( { email: email },
      (err, user) => {
      // modify your "data", probably with a callback chain

在其他功能上,您可以使用user.save() 当然,有$set解决方法,但是如果您只想为用户完成一个简单的更新,那就太过分了。 通过这种方法,我什至可以在使用过程中轻松地使用async库在用户记录上链接一系列更新。

暂无
暂无

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

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