[英]Update user.profile with dynamic object in Meteor
So, what I'm trying to achieve is to update the user.profile
keeping the old non updated data already present in the user.profile
. 所以,我想要实现的是更新
user.profile
使旧的未更新数据已经存在于user.profile
。
So, my initial user.profile
has the following: 因此,我的初始
user.profile
具有以下内容:
{
accountType: 'Student',
xyz: 'something',
etc...
}
And in my update method I would like to keep those values if not required to be updated, so if I wish to add the following: 在我的更新方法中,如果不需要更新,我想保留这些值,因此,如果要添加以下内容:
{
'xyz': 'something else',
'bar': 'bar',
etc...
}
I would like to see the updated profile with both object merged and updated. 我希望看到具有合并和更新的对象的更新的配置文件。
What I tried to use is update
and upsert
but in both cases and all my tests when I try to update the user.profile
the old data get completely replaced by the new data... 我尝试使用的是
update
和upsert
但是在两种情况下以及我尝试更新user.profile
时的所有测试中,旧数据都被新数据完全替换了...
Here is one of my latest try: 这是我最近的尝试之一:
Meteor.users.update(this.userId, {
$set: {
profile: data
}
},
{ upsert: true });
but I also tried: 但我也尝试过:
Meteor.users.upsert(this.userId, {
$set: {
profile: data
}
});
How can I achieve what I need? 我怎样才能达到我所需要的? Thanks
谢谢
From the Mongo documentation : 从Mongo文档中 :
The $set operator replaces the value of a field with the specified value.
$ set运算符用指定的值替换字段的值。
Thus, when you're updating it as { $set: { profile: ... } }
it replaces the whole profile
document. 因此,当您将其更新为
{ $set: { profile: ... } }
它将替换整个profile
文件。
You should use it like this: 您应该这样使用它:
$set: {
'profile.<field_name>': '<field_value>',
...
}
Here is the code to do that for your case: 这是针对您的情况的代码:
const $set = {};
_.each(data, (value, key) => {
$set[`profile.${key}`] = value;
});
Meteor.users.update(this.userId, { $set });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.