How to set mongo field from variable

2019-01-24 06:17发布

问题:

for(var key in resp.updated_items){
    Meteor.users.update({backend_id: Meteor.user().backend_id},
    {$set: {'profile': {key: resp.updated_items[key]}}});
}

And this query set proper information to key key. But how can I assign 'real' value of key?

回答1:

Basics:

var obj = {key: 'value'}; //prints {key: "value"}
var obj2 = {};
var key = 'someKey';
obj2[key] = 'someValue';
//{someKey: 'someValue'}

Try this: (You have to use [] for that.)

for(var key in resp.updated_items){
  var set = {profile: {}};
  set.profile[key] = resp.updated_items[key];
  Meteor.users.update({backend_id: Meteor.user().backend_id},
  {$set: set});
}

I am not able to remeber how set works in meteor. But in mongo, you have to do something like this:

for(var key in resp.updated_items){
  var set = {};
  set['profile.' + key] = resp.updated_items[key];
  Meteor.users.update({backend_id: Meteor.user().backend_id},
  {$set: set});
}


回答2:

If you have only one value to update

updateUserData: function(userId, key, value) {
            this.unblock();
            let set = {};
            set[key] = value;
            Meteor.users.update({
                _id: userId
            }, {$set: set});

            return true;

        }