使用Meteor中的动态对象更新user.profile

时间:2017-08-07 14:09:55

标签: 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
  }
});

我如何实现我的需要?感谢

1 个答案:

答案 0 :(得分:2)

来自Mongo documentation

  

$ set运算符用指定的值替换字段的值。

因此,当您将其更新为{ $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 });