Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically update/set a sub attribute of a Collection in Meteor?

I would like to specify in my code which attribute to set/update in a DB update dynamically. Something like this:

var fieldname = "firstname"
var name = "loomi"
Meteor.users.update({_id:Meteor.user()._id},
                    {$set:{"profile."+fieldname: name}})

(profile[fieldname] does not work btw.)

The result of the above should do the same as this:

Meteor.users.update({_id:Meteor.user()._id},
                       {$set:{"profile.firstname": "loomi"}})

How can I achieve this in a neat way, please? (Without getting the whole object doing manipulations and sending the whole object back.)

like image 440
loomi Avatar asked Dec 04 '22 12:12

loomi


1 Answers

You can't currently define variable keys within an object literal. You'll instead have to build the object, then pass it:

var $set = {};
$set['profile.' + fieldname] = name;
Meteor.users.update({_id:Meteor.user()._id}, { $set: $set });

[Update]

ECMAScript 6 has defined support for computed keys within object literals/initializers.

So, with an ES6-compatible engine, this can now be written as:

Meteor.users.update(
    { _id: Meteor.user()._id },
    { $set: { ['profile.' + fieldname]: name } }
);
like image 63
Jonathan Lonowski Avatar answered Dec 28 '22 09:12

Jonathan Lonowski