Reputation: 3476
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
.
So, my initial user.profile
has the following:
{
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...
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
Upvotes: 1
Views: 35
Reputation: 10076
From the Mongo documentation:
The $set operator replaces the value of a field with the specified value.
Thus, when you're updating it as { $set: { profile: ... } }
it replaces the whole profile
document.
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 });
Upvotes: 2