How can I retrieve the value of one variable using a dynamic variable in Meteor?

Currently, I am striving to enhance the modularity of my code for the sake of organization and efficiency. However, I have hit a roadblock due to a lack of knowledge in JavaScript.

I have a method call that pertains to purchasing different types of units. Before training a more advanced type like citizen.workers or soldier.specific, I need to verify if the player possesses enough of a particular type of unit, either citizens or soldiers. Right now, I am only focusing on determining if the base unit is available in the required quantity.

The current approach that I am using seems to be ineffective. The 'type' variable does not seem to evaluate properly; instead, it defaults to "type" when it should default as "citizens". This variable is used in two instances - within the if statement for evaluation and in the database update to decrement the specific field.

Here is the existing 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;
},

I have searched extensively but have been unable to find a solution or even a starting point to address my needs. Any assistance would be greatly appreciated.

Edit: I acknowledge the mistake in utilizing a default value in JavaScript incorrectly. I have rectified this in my code. The computed value provided by David Weldon in his response aligns closely with what I am aiming to achieve.

Answer №1

Make the necessary adjustments to your code:

player[type] >= number

as well as

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

The latter example showcases a computed property key feature that was introduced in ES6.

For more information, refer to the 'Variables as Keys' segment on common mistakes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change the output of Object.fromEntries

I've been working on updating the values of an object using the .fromEntries() method. The issue I am facing is that even though I am returning a modified Array of hours, when the function completes it reverts back to the original complete Array. If ...

Transforming the color of a globe from black to white with gio js

After searching for a solution to change the color of a Three.js globe, I came across a link that didn't work as expected: Change the color of a Three.js globe. My goal is to change the globe color from black to white using . I attempted to use the f ...

RaphaelJS: Ensuring Consistent Size of SVG Path Shapes

I am currently constructing a website that features an SVG map of the United States using the user-friendly usmap jQuery plugin powered by Raphael. An event is triggered when an individual state on the map is clicked. However, when rendering a single stat ...

What occurs when a function component is passed as a state variable?

Can a function component be passed as a state variable? Is it possible for the code below to work correctly? I attempted it but encountered an error stating props.children isn't a function. Do you know if this approach can be successful? const App = ...

How can I run JavaScript code written in the Chrome console on standalone Node.js platform

After successfully creating a script that functions when input into the Google Chrome developer console, I now desire to convert it into an executable file. My goal is to open the file and have it log all activity in a separate node.js console window, whil ...

What is causing the col divs to stack instead of aligning next to each other?

I am a newcomer to Vue.JS and front-end programming in general. I wanted to create a page with a fixed sidebar and content below a navbar. Here is the configuration I tried: <template> <div class="container-fluid"> <div class ...

Extracting the value from a Text Editor in React Js: [Code snippet provided]

Currently, I am in the process of developing a basic app that generates a JSON form. So far, I have successfully incorporated sections for basic details and employment information. The basic details section consists of two input fields: First Name and Las ...

Error message in Vuex4: Unable to access 'state' property because it is undefined

Having trouble with Vue3 and Vuex4, I keep encountering this error: Uncaught TypeError: Cannot read properties of undefined (reading 'state') at ReactiveEffect.eval [as fn] (App.vue?3dfd:36) at ReactiveEffect.run (reactivity.esm-bundler.j ...

Guide on saving an Express session into a MongoDB database through a controller handling

I'm experiencing a problem with my controller where the session is not being stored properly even after implementing the necessary express session code app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, ...

Pause for a moment before displaying the VueJS loading screen

When using VueJS, I have implemented a loader to be displayed on each route like this: router.beforeEach((to, from, next) => { store.commit('loading', true); next(); }) However, it seems unnecessary to show the loader for a request that ...

"Exploring the power of mongoose getters combined with the magic

Imagine having a Person model where the schema includes a phone number key with a getter for formatting. After retrieving a document from the database and checking the value using console.log(doc.phone), you will see a properly formatted phone number. Howe ...

Managing various dropdown select options in pure JavaScript

Consider the select element provided below: <select multiple="multiple"> <option value="car">car</option> <option value="scooter">scooter</option> <option value="bus">bus</option> </select> I ...

creating an identical copy of a dynamic element's size

I am currently working on a project using react js where I need to incorporate multiple images. My goal is to have standard background divs / rectangles that match the exact size of each image, allowing for animations to be performed on top of them. The sn ...

Iterate through an array to extract specific objects and exclude them from another array

Within my code, I have an array named allItems that stores objects. allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ] I am seeking a way to filter out the objects from th ...

Having trouble with my Slack Bot development due to an unexpected error

While attempting to create a Slack Bot in Node, I consistently encounter an error when running npm start in my terminal: The error seems to be located in the Vow.js file. Despite double-checking everything, I can't seem to pinpoint the issue. For gui ...

Is combining Laravel, laravel-mongodb, and lighthouse (graphql) a good idea?

Would it be possible to integrate Laravel 11 with Lighthouse-php and MongoDB (using laravel-mongodb)? I am interested in linking my Laravel 11 application with MongoDB Atlas and retrieving data using GraphQL. I have previously managed to connect it with M ...

Developing Modules in NodeJS using Constructors or Object Literals

I am currently developing a nodejs application that needs to communicate with various network resources, such as cache services and databases. To achieve this functionality, I have created a module imported through the require statement, which allows the a ...

Utilize the splice function when resizing the window based on specific breakpoints

On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row. <div class="element"></div> <div class="element"></div> <div class ...

changing the vertical position of an element using JavaScript

I'm currently working on a project where I have a canvas that animates upwards when a button is clicked. However, I'm facing an issue with making it go back down after the animation completes. It seems to be getting stuck and not returning to its ...

Studio 3T chooses all elements within an array column

I have a database collection stored in Mongo with the following schema (simplified): { "_id" : ObjectId("55a94615a243a426db43d81e"), "property_name" : "My Main Property", "domain_list" : [ "mynumber1url.com", "mynumber2url.c ...