所以,我想要实现的是更新 user.profile
,保留 user.profile
中已经存在的旧的未更新数据。
因此,我的初始 user.profile
具有以下内容:
{
accountType: 'Student',
xyz: 'something',
etc...
}
在我的更新方法中,如果不需要更新,我想保留这些值,所以如果我想添加以下内容:
{
'xyz': 'something else',
'bar': 'bar',
etc...
}
我希望看到更新后的配置文件,其中包含对象合并和更新。
我尝试使用的是 update
和 upsert
但在这两种情况下以及我尝试更新 user.profile
时的所有测试旧数据完全被新数据取代...
这是我最近的尝试之一:
Meteor.users.update(this.userId, {
$set: {
profile: data
}
},
{ upsert: true });
但我也试过:
Meteor.users.upsert(this.userId, {
$set: {
profile: data
}
});
我怎样才能达到我的需要?谢谢
最佳答案
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/