Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在MongoDB update语句中使用变量_Javascript_Mongodb_Meteor - Fatal编程技术网

Javascript 在MongoDB update语句中使用变量

Javascript 在MongoDB update语句中使用变量,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,我试图在update语句中使用变量作为字段名,但它根本不起作用,有什么建议吗 例如: COLLECTIONNAME.update( {{u id:this.{u id}, {$set:{VARIABLE1:VARIABLE2} ); 实际代码: “blur.editable”:函数(){ var target=event.currentTarget.value; var字段=event.currentTarget.name; 字段='“'+字段+'”; update({u id:this.{u

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

例如:

COLLECTIONNAME.update(
{{u id:this.{u id},
{$set:{VARIABLE1:VARIABLE2}
);
实际代码:

“blur.editable”:函数(){
var target=event.currentTarget.value;
var字段=event.currentTarget.name;
字段='“'+字段+'”;
update({u id:this.{u id},{$set:{field:target}});
}

您可以这样做:

'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

如果使用第二种方法,您可以使用变量访问它,以进行查询
COLLECTIONNAME.update({u-id:this.{u-id},{$set:{VARIABLE1:VARIABLE2})
MangGDB将使用ValueL2的值,但是它会考虑“变量1”是文档中的一个字段。
用于传递值为字段名的变量:

您必须创建一个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 } );
根据的评论,我发现对字段值使用
[]
是可行的

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

美丽的!我只需要删除这一行:field='“+field+'”;它工作得很好。非常感谢<代码>Hostings.update({u id:this.{u id},{$set:{[field]:target})也可以
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}}) 
})