【问题标题】:Using variables in MongoDB update statement在 MongoDB 更新语句中使用变量
【发布时间】:2013-09-01 10:57:33
【问题描述】:

我试图在更新语句中使用变量作为字段名称,但它根本不起作用,有什么建议吗?

例如:

COLLECTIONNAME.update(
    { _id: this._id },
    { $set: { VARIABLE1 : VARIABLE2 } }
);

实际代码:

 'blur .editable' : function () {
      var target = event.currentTarget.value;
      var field = event.currentTarget.name;
      field = ' " ' + field + ' " ';
      Hostings.update( { _id: this._id },{ $set: { field : target } } );
    }

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    你可以这样做:

    'blur .editable' : function () {
      var target = event.currentTarget.value;
      var field = event.currentTarget.name;
    
      var obj = {};
          obj[field] = target;
      Hostings.update( { _id: this._id },{ $set: obj } );
    }
    

    可以通过两种方式访问​​ Javascrip 对象:

    object.attribute
    

    object["attribute"]
    

    如果您使用第二种方法,您可以使用变量访问它

    【讨论】:

    • 漂亮!我只需要删除这一行: field = ' " ' + field + ' " ';它工作得很好。非常感谢!
    • Hostings.update( { _id: this._id },{ $set: { [field]: target } } ); 也可以
    【解决方案2】:

    根据L. Norman 的评论,我发现使用[] 作为字段值可以代替

    collection = "my_collection"
    db.getCollection(collection).find({}).forEach(function(doc) {
        var new_field = "new_field";
        var new_value = "new_value";
    
        db.getCollection(collection).update({_id: doc._id}, 
            {$set: {[new_field] : new_value}}) 
    })
    

    【讨论】:

    • 这是最简单的解决方案。将字段值放在 [ ] 中是解决我遇到的相同问题的方法。
    【解决方案3】:

    为您查询
    COLLECTIONNAME.update( { _id: this._id },{ $set: { VARIABLE1 : VARIABLE2 } } ); mongodb 将采用 VARIABLE2 的值,但它会将“VARIABLE1”视为文档中的一个字段。

    用于传递值为字段名称的变量:

    您必须创建一个 javascript 对象并按如下方式使用它:

    var obj={};
    obj[VARIABLE1] = VARIABLE2; //where VARIABLE1 and VARIABLE2 are getting values from elsewhere earlier
    

    如果你想以这种方式拥有多个字段,只需将其添加到同一个对象:

    obj[VARIABLE3]= VARIABLE4;
    

    然后进行更新操作为:

    db.collectionname.update( { _id: this._id },{ $set: obj } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多