用mongodb dotnotation来variables

我想增加一个蒙古文档内的对象对象内的字段1。

var stuffID = 5 collection.update({ "id": id, }, { '$inc': { 'stuff.stuffID': 1 } }, function(err, doc) { res.end('done'); }); 

我需要使stuffidvariables。 任何方式来做到这一点? 谢谢。

这是使用节点mongodb本地如果有帮助。

如果你投票结束,你能解释一下你不明白的东西吗?

您需要单独创build可变键控对象,因为ES2015之前的JS不允许使用对象字面量语法中的常量string:

 var stuffID = 5 var stuff = {}; // create an empty object stuff['stuff.' + stuffID] = 1; // and then populate the variable key collection.update({ "id": id, }, { "$inc": stuff // pass the object from above here }, ...); 

在ES2015中编辑 ,现在可以使用expression式作为对象字面值中的一个键,使用[expr]: value语法,在这种情况下也使用ES2015反向string插值:

 var stuffID = 5; collection.update({ "id": id, }, { "$inc": { [`stuff.${stuffID}`]: 1 } }, ...); 

上面的代码在Node.js v4 +中工作

把variables放在说stuffID的地方。

 'stuff.' + varname: 1