Javascript 使用变量(MongoDB,Node,Inc)访问嵌套数组中的嵌套对象
我知道与这个问题相关的话题很多,但似乎没有一个能回答我的问题。它与Node和Mongo有关,但我认为这是一个普遍的Javascript问题 在MongoDB中,我需要使用一个变量访问Javascript 使用变量(MongoDB,Node,Inc)访问嵌套数组中的嵌套对象,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我知道与这个问题相关的话题很多,但似乎没有一个能回答我的问题。它与Node和Mongo有关,但我认为这是一个普遍的Javascript问题 在MongoDB中,我需要使用一个变量访问选项数组,该变量给出索引号,然后增加它的投票属性。例如: { "_id": { "$oid": "58ce7c6c39aff90a7c66b0d4" }, "question": "Test", "options": [ { "a
选项
数组,该变量给出索引号,然后增加它的投票
属性。例如:
{
"_id": {
"$oid": "58ce7c6c39aff90a7c66b0d4"
},
"question": "Test",
"options": [
{
"answer": "answer1",
"option": "Bob Dylan",
"votes": 2
},
{
"answer": "answer2",
"option": "Bob Geldof",
"votes": 0
}
]
}
var inc = {};
inc["options[" + index + "].votes"] = 1;
然后,我得到需要更新的数组的索引,如下所示:
var votedFor = "answer2";
votedFor = votedFor.match(/\d+/)[0];
var index = parseInt(votedFor) - 1;
db.collection('questions')
.findOneAndUpdate({"_id": questionId}, {$inc : inc }, (err, result) => {
if (err) return res.send(err)
res.send(result)
})
然后我假设整数的路径是:
{
"_id": {
"$oid": "58ce7c6c39aff90a7c66b0d4"
},
"question": "Test",
"options": [
{
"answer": "answer1",
"option": "Bob Dylan",
"votes": 2
},
{
"answer": "answer2",
"option": "Bob Geldof",
"votes": 0
}
]
}
var inc = {};
inc["options[" + index + "].votes"] = 1;
我想这样说:
var votedFor = "answer2";
votedFor = votedFor.match(/\d+/)[0];
var index = parseInt(votedFor) - 1;
db.collection('questions')
.findOneAndUpdate({"_id": questionId}, {$inc : inc }, (err, result) => {
if (err) return res.send(err)
res.send(result)
})
这将更新数据库,如下所示:
{
"_id": {
"$oid": "58ce7c6c39aff90a7c66b0d4"
},
"question": "Test",
"options": [
{
"answer": "answer1",
"option": "Bob Dylan",
"votes": 2
},
{
"answer": "answer2",
"option": "Bob Geldof",
"votes": 0
}
],
"options[1]": {
"votes": 1
}
}
正如您所看到的,与递增的options[1]相反,它创建了一个新属性
有没有办法用这样的变量访问数组索引?而不是执行以下操作:
var inc={};
inc[“期权[”+指数+“].投票”]=1;
你应该做:
var inc={};
inc[“期权”+“指数”+“投票”]=1;
因此,您不应该使用选项[0]。投票
,而应该使用选项。1.投票
,这就是MongoDB中数组更新的方式。而不是执行以下操作:
var inc={};
inc[“期权[”+指数+“].投票”]=1;
你应该做:
var inc={};
inc[“期权”+“指数”+“投票”]=1;
因此,您不应该使用选项[0]。投票
,而应该使用选项。1.投票
,这就是在MongoDB中进行阵列更新的方式。阅读有关处理阵列更新的信息
db.collection.update({'_id': questionId, 'options.answer':'answer2'},{"$inc":{"options.$.votes":1}})
请阅读有关处理阵列更新的信息
db.collection.update({'_id': questionId, 'options.answer':'answer2'},{"$inc":{"options.$.votes":1}})
可能的重复可能的重复