Search code examples
javascriptmongodbmeteorminimongo

Using a dynamic variable to access another variable's value in Meteor?


So I'm trying to make my code more modular for sanity purposes (and because it seems more efficient than writing the same code five+ different ways).

However, I'm running against a wall on this one as my JavaScript knowledge is apparently lacking. I've got a method call for buying various unit types. I want to check that the player has enough of a particular type of unit citizens or soldiers before training a more advanced type citizen.workers or soldier.specific. Incrementing the more advanced type isn't a problem I'm addressing yet; I'm simply trying to determine if the base unit is present in a minimum quantity.

What I'm currently using is not working. The type variable is not evaluating but is rather going through as "type" when I want it to default as "citizens". I'm using the variable in 2 places, the if statement for evaluation purposes and in the DB update to reduce the number of that particular field.

Current code:

'buy': function(cost, number, type) {
  type = type || "citizens";
  var currentUser = Meteor.user();
  var player = Players.findOne({createdBy: currentUser._id});
  if(player.credits >= cost && cost > 0 && player.type >= number && number > 0) {
    Players.update({createdBy: currentUser._id}, {$inc: {'credits': (0-cost), type: (0-number)}});
    return true;
  }
  return false;
},

Searched all over but was not finding what I was looking for or even something I could start with and begin to apply it to what I needed. Any help would be great.

Edit: Yes I realized I was using a default value incorrectly for javascript. I've modified that in my code. The computed value David Weldon answered with was what I was going after more specifically.


Solution

  • Change your code in the following ways:

    player[type] >= number

    and

    {$inc: {'credits': (0-cost), [type]: (0-number)}}

    The latter is an example of a computed property key which is new in es6.

    Also see the 'Variables as Keys' section of common mistakes.