mongodb / javascript variable in query

时间:2016-08-31 17:51:37

标签: javascript mongodb

i have:

var optiontable = {1: 'attack', 2: 'defence', 3: 'intelligence'};
    var option = 1;
    var minion = minions[thisminion]; // get correct, works.
    console.log(optiontable[option]); // would output "attack"
    var nameoption = optiontable[option];
var increasement = 8;

how would i do to get the minion.attack based on:

thisminion.nameoption  // this wont work when it should display the result of thisminion.attack

and get the nameoption to use in:

      minions.update({
                    _id: thisminion._id,
                    userid: playerid
                }, {$inc: {nameoption: increasement}})

1 个答案:

答案 0 :(得分:1)

Hard to tell without looking at the rest of the code, but looks like you just need to change

thisminion.nameoption

to

thisminion[nameoption]

Since your original line is trying to access thisminion's property called 'nameoption'. Using square brackets would access the property named the same as the value of nameoption.

As for the mongo part: since you can't use a variable as left-hand value, you need to do a little bit of extra work:

var updateObj = {};
updateObj[nameoption] = increasement;

then you can do this:

 minions.update({
                    _id: thisminion._id,
                    userid: playerid
                }, {$inc: updateObj})

Similar questions:

How to set mongo field from variable

Using variables in MongoDB update statement