【问题标题】:How to dynamically update/set a sub attribute of a Collection in Meteor?如何在 Meteor 中动态更新/设置集合的子属性?
【发布时间】:2015-05-30 06:33:11
【问题描述】:

我想在我的代码中指定在数据库更新中动态设置/更新的属性。像这样的:

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

(profile[fieldname] 顺便说一句不起作用。)

上面的结果应该和这个一样:

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

请问我怎样才能以一种简洁的方式实现这一点? (没有让整个对象进行操作并将整个对象发回。)

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    您目前无法在对象字面量中定义变量键。相反,您必须构建对象,然后传递它:

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

    [更新]

    ECMAScript 6 在对象字面量/初始化器中定义了对computed keys 的支持。

    所以,有了ES6-compatible engine,现在可以写成:

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

    【讨论】:

    • Meteor 1.2 现在默认支持新项目的 ES6(重命名为 ES2015)。较旧的项目可以通过 meteor add ecmascript 添加支持
    【解决方案2】:

    这对我有用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      • 2014-04-06
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      相关资源
      最近更新 更多