我正在制作投票系统,投票是通过链接完成的。在我的index.js中,我得到了所需的值并将它们放在变量中。 “type”变量代表我的mongodb中需要更新的字段,我把它放在一个变量中,因为它取决于点击了哪个链接。
现在在$ set函数中,他们需要db字段和一个新值,因为我使用变量但我的“type”变量不起作用。当我去我的mongodb时,会创建一个名为“type”的新表。怎么解决这个问题?
router.get('/vote/:Id/:Value/:Type', function(req, res) {
var db = req.db;
var id = req.params.Id;
var type = req.params.Type;
var value = parseInt(req.params.Value);
var newValue = value + 1;
var collection = db.get('games');
collection.update(
{"_id" : id},
{$set: {type: newValue}}
, function (err, doc) {
if (err) {
res.send("There was a problem");
}
else {
res.location("../../../admin");
res.redirect("../../../admin");
}
});
});
答案 0 :(得分:5)
在javascript中,您不能将变量用作对象文字中的属性名称,而这是您尝试做的事情。
试一试:
var a = 'someProperty';
var o = {a: 'somePropertyValue'};
console.log(o);
将打印{ a: 'somePropertyValue' }
而不是{someProperty:'somePropertyValue}
。
如果javascript允许在对象文字表示法中引用属性名称中的变量,则必须删除不带引号的名称,因为这些名称会产生歧义。
a
应该用作属性的值,还是应该是变量a
的值?
尝试使用事先创建的对象创建更新对象文字,而不使用对象文字表示法,因此您的代码如下所示:
router.get('/vote/:Id/:Value/:Type', function(req, res) {
var db = req.db;
var id = req.params.Id;
var type = req.params.Type;
var value = parseInt(req.params.Value);
var newValue = value + 1;
var collection = db.get('games');
//We create the $set property/value pair using property assignment, not the object literal
var updateVal = {};
updateVal[type] = newValue;
collection.update(
{"_id" : id},
{$set: updateVal} //use it here
, function (err, doc) {
if (err) {
res.send("There was a problem");
}
else {
res.location("../../../admin");
res.redirect("../../../admin");
}
}
);
});
更好的是,事先构建整个$set
操作。