简体   繁体   中英

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 .

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

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM