在MongoDB更新语句中使用变量

gla*_*ses 6 javascript mongodb meteor

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

例如:

COLLECTIONNAME.update(
    { _id: this._id },
    { $set: { VARIABLE1 : VARIABLE2 } }
);
Run Code Online (Sandbox Code Playgroud)

实际代码:

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

Jon*_*owe 13

你可以这样做:

'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 } );
}
Run Code Online (Sandbox Code Playgroud)

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

object.attribute
Run Code Online (Sandbox Code Playgroud)

要么

object["attribute"]
Run Code Online (Sandbox Code Playgroud)

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

  • `Hostings.update( { _id: this._id },{ $set: { [field]: target } } );` 也可以 (3认同)

Yi *_*ong 5

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

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}}) 
})
Run Code Online (Sandbox Code Playgroud)