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.)
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 } }
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With