javascript - 在 Meteor 中使用动态对象更新 user.profile

标签 javascript meteor

所以,我想要实现的是更新 user.profile,保留 user.profile 中已经存在的旧的未更新数据。

因此,我的初始 user.profile 具有以下内容:

{
  accountType: 'Student',
  xyz: 'something',
  etc...
}

在我的更新方法中,如果不需要更新,我想保留这些值,所以如果我想添加以下内容:

{
  'xyz': 'something else',
  'bar': 'bar',
  etc...
}

我希望看到更新后的配置文件,其中包含对象合并和更新。

我尝试使用的是 updateupsert 但在这两种情况下以及我尝试更新 user.profile 时的所有测试旧数据完全被新数据取代...

这是我最近的尝试之一:

Meteor.users.update(this.userId, {
  $set: {
    profile: data
  }
},
{ upsert: true });

但我也试过:

Meteor.users.upsert(this.userId, {
  $set: {
    profile: data
  }
});

我怎样才能达到我的需要?谢谢

最佳答案

来自Mongo documentation :

The $set operator replaces the value of a field with the specified value.

因此,当您将其更新为 { $set: { profile: ... } } 时,它会替换整个 profile 文档。

你应该像这样使用它:

$set: {
  'profile.<field_name>': '<field_value>',
  ...
}

这是为您的案例执行此操作的代码:

const $set = {};
_.each(data, (value, key) => {
  $set[`profile.${key}`] = value;
});
Meteor.users.update(this.userId, { $set });

关于javascript - 在 Meteor 中使用动态对象更新 user.profile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45548977/

相关文章:

javascript - 流畅刷新页面

javascript - 使用 &lt;title&gt; 标签内容填充 &lt;input&gt; 元素

javascript - 如何使用 Meteor Template Helper 增加和显示变量计数器?

html - Container Fluid 上的高度不是 100%,即使 html 和 body 是

meteor - 集合FS : Images not defined

javascript - 如何使用javascript打印到控制台?

javascript - JavaScript 中的 Promise 顺序

javascript - 如何检查和分割二进制中的整数前缀?

meteor - Uncaught ReferenceError : require is not defined in Meteor

meteor > 错误 : no such package: 'accounts-urls'