变量与mongodb dotnotation [英] variable with mongodb dotnotation
问题描述
我想将mongodb文档中对象对象内的字段增加1。
I want to increase a field inside an object object inside a mongodb document by 1.
var stuffID = 5
collection.update({
"id": id,
},
{
'$inc': {
'stuff.stuffID': 1
}
},
function(err, doc) {
res.end('done');
});
我需要将那个stuffID变成一个变量。有办法吗?谢谢。
I need to make that stuffID a variable. Any way to do that? Thanks.
如果有帮助的话,这是使用node-mongodb-native。
This is using node-mongodb-native if that helps.
如果你投票给你能解释一下你不明白的东西吗?
If you're voting to close can you explain what it is you don't understand?
推荐答案
你需要分别创建你的可变键控对象,因为在ES2015之前的JS不允许除了对象文字语法中的常量字符串之外的任何内容:
You need to create your variably-keyed object separately, because JS before ES2015 doesn't permit anything other than constant strings in object literal syntax:
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
}, ...);
编辑,现在可以将表达式用作关键字在对象文字中,使用 [expr]:value
语法,在这种情况下也使用ES2015反引号字符串插值:
EDIT in ES2015, it's now possible to use an expression as a key in an object literal, using [expr]: value
syntax, and in this case also using ES2015 backtick string interpolation:
var stuffID = 5;
collection.update({
"id": id,
}, {
"$inc": {
[`stuff.${stuffID}`]: 1
}
}, ...);
以上代码适用于Node.js v4 +
The code above works in Node.js v4+
这篇关于变量与mongodb dotnotation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!