How to dynamically update / set the sub attribute in a collection in Meteor?

I would like to indicate in my code an attribute for installing / updating in updating the database dynamically. Something like that:

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

(profile [file_name] does not work.)

The result above should be the same:

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

How can I do this carefully, please? (Without the whole object doing the manipulation and sending the whole object back.)

+4
source share
2 answers

It is currently not possible to define variables in an object literal. Instead, you have to build an object and then pass it:

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

[Update]

ECMAScript 6 defines support for computed keys in 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 } } ); 
+15
source

Here is what worked for me:

  var $set = {}; $set['profile.fieldname'] = 'the name'; Meteor.users.update({_id:Meteor.user()._id}, { $set: $set }, function(error){ if(error) console.log(error.reason) }); 
0
source

All Articles