使用$ set中的变量使用node.js更新mongodb

Kim*_*ens 5 javascript mongodb node.js

我正在制作投票系统,投票是通过链接完成的.在我的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");
    }
});
Run Code Online (Sandbox Code Playgroud)

});

sou*_*eck 5

在javascript中,您不能将变量用作对象常量中的属性名称,而这就是您要尝试做的事情。

试试吧:

var a = 'someProperty';

var o = {a: 'somePropertyValue'};

console.log(o);
Run Code Online (Sandbox Code Playgroud)

将打印{ 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");
            }
        }
    );
});
Run Code Online (Sandbox Code Playgroud)

更好的是,$set事先构造整个操作。