简体   繁体   中英

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.)

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

Here's 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)
    });

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