Har*_*rry 8 javascript mongodb node.js
我想将mongodb文档中的对象对象内的字段增加1.
var stuffID = 5
collection.update({
"id": id,
},
{
'$inc': {
'stuff.stuffID': 1
}
},
function(err, doc) {
res.end('done');
});
Run Code Online (Sandbox Code Playgroud)
我需要将那个stuffID变成一个变量.有办法吗?谢谢.
如果有帮助,这是使用node-mongodb-native.
如果你投票结束,你能解释一下你不明白吗?
Aln*_*tak 13
您需要单独创建可变键控对象,因为JS之前ES2015不允许低于对象文字语法常量字符串的任何其他:
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
}, ...);
Run Code Online (Sandbox Code Playgroud)
在ES2015中编辑,现在可以使用表达式作为对象文字中的键,使用[expr]: value
语法,在这种情况下也使用ES2015反引号字符串插值:
var stuffID = 5;
collection.update({
"id": id,
}, {
"$inc": {
[`stuff.${stuffID}`]: 1
}
}, ...);
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于Node.js v4 +