各位,
我正在尝试使用 $rename
运算符 ( 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 中使用变量来指定事物?
谢谢
最佳答案
尝试这样:
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}
这样的引号,所以不可能在那里使用一个变量。但您可以像我的代码示例中那样单独构建对象。
另外,请注意变量 this
是一个特殊关键字。不要使用 this
作为常规变量名称。语法高亮甚至有不同的颜色!请使用不同的名称。
关于javascript - MongoDB $rename javascript 变量作为键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23769644/