update mongodb with node.js using a variable in $set

javascript, mongodb, node.js

Solution

In javascript you cannot use variables as property names in object literals, and that's what you're trying to do.

Try it:

var a = 'someProperty';

var o = {a: 'somePropertyValue'};

console.log(o);

will print `{ a: 'somePropertyValue' }` not `{someProperty:'somePropertyValue}`.

If javascript permitted referencing variables in property names in object literal notation it would have to get rid of unquoted names as those would create ambiguity. Should `a` be used as the value of the property or should it be the value of the variable `a`?

Try creating the update object literal with an object crated beforehand without the usage of object literal notation, so your code looks something like this:

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");
            }
        }
    );
});

Even better, construct the whole `$set` operation beforehand.

Problem

I am making a voting system, the voting is done with a link. In my index.js I get the required values and put them in variables. The "type" variable stands for the field in my mongodb wich needs to be updated, I have put it in a variable because it depends on which link is clicked. Now in the $set function they require the db field and a new value, for both I use variables but my "type" variable doesn't work. And when I go to my mongodb there is a new table created called "type". How can this be solved? ``` 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"); } }); ``` });

Original source