MongoDB $rename javascript 变量的键名 [英] MongoDB $rename javascript variable for key name
问题描述
各位,我正在尝试使用 $rename
运算符 (http://docs.mongodb.org/manual/reference/operator/update/rename/)
Folks,
I am trying to use the $rename
operator (http://docs.mongodb.org/manual/reference/operator/update/rename/)
作品:
collection.update( {_id: id}, {$rename: {'foo': 'bar'} } , function (err, result) {});
不会:
var this = 'foo';
var that = 'bar';
collection.update( {_id: id}, {$rename: {this: that} } , function (err, result) {});
为什么不允许我在 mongoclient 中使用变量来指定事物?
Why am I not allowed to use variables in the mongoclient to specify things?
谢谢
推荐答案
试试这个:
var this = 'foo';
var that = 'bar';
var rename_query = {'$rename': {}};
rename_query['$rename'][this] = that;
collection.update( {_id: id}, rename_query , function (err, result) {});
问题在于对象构造函数{foo:bar}
,key隐含了像{'foo':bar}
这样的引号,所以不可能在那里使用一个变量.但是您可以像在我的代码示例中一样单独构建对象.
The issue is that the object constructor {foo: bar}
, the key implies the quotation marks like {'foo': bar}
so it is not possible to use a variable there. But you can build the object separately like in my code example.
另外,请注意变量 this
是一个特殊的关键字.不要使用 this
作为常规变量名.语法高亮甚至有不同的颜色!请使用其他名称.
Also, beware that the variable this
is a special keyword. Do not use this
as a regular variable name. The syntax highlighting even has it in a different color! Please use a different name.
这篇关于MongoDB $rename javascript 变量的键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!