Using a JavaScript variable in a MongoDB query

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 can I retrieve the minion.attack using the following notation:

thisminion.nameoption  // this expression is not functional as it should display the result of thisminion.attack

and how can I use the value of nameoption in the following context:

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

Answer №1

It's a bit tricky to say without seeing the entire code, but it seems like all you need to do is make a simple change

thisminion.nameoption

to

thisminion[nameoption]

The original line is attempting to access a property called 'nameoption' in thisminion. By using square brackets, you'll be able to access the property named after the value of nameoption.

Regarding the Mongo aspect: since you can't directly use a variable as a left-hand value, you'll have to take an extra step:

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

Then you can execute:

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

Related queries:

How to set mongo field from variable

Using variables in MongoDB update statement

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

How can we use regex to find and replace hashtags, excluding the hashtag symbol?

I am struggling with the following function: function formattedTitle(posttitle,hreflink) { return `<a href='`+ hreflink +`'>` + posttitle.replace(/(^|\s)(#[-.\w]+)/gi, `$1</a><a class="hashtag" href='/search?q=has ...

Establishing the highest allowable value limit in cleave

I've integrated cleave.js into my Vue.js project to create a date input field. Here's the option configuration I used: <cleave :options="{ date: true, datePattern: ['m', 'd','Y'] ...

The Jquery click event is not triggering after the initial click

I am dealing with some HTML content: <div class="post-container self"> <a href="/user/Wiz"> <img class="avatar" alt="Profile Picture" src=""> </a> <div class="post-body"> <div class="post" style ...

Adjust the top margin of a div to match the height of the screen within an iframe, ensuring cross-browser

Trying to adjust the margin-top of a div to 100% of screen height within an iframe seems to be causing issues with jQuery, as it either returns 0 or inaccurate values. While CSS3's 100vh can work as an alternative, it may not be supported in older an ...

What are effective ways to eliminate cross-origin request restrictions in Chrome?

Just starting out with angular and trying to incorporate a templateUrl in an angular directive. However, when attempting to view the local html file in the browser, I encounter the following errors --> XMLHttpRequest cannot load file:///Users/suparnade ...

Is there a way to automatically change the value of one input box to its negative counterpart when either of the two input boxes have been filled in?

Consider two input boxes: box1 box2 If a user enters a number in one of the input boxes, we want the value of the other input box to automatically change to the opposite sign of that number. For example: User enters 3 in box1. The value of box2 shoul ...

Error: SyntaxError - Issue with the AJAX request

When attempting to retrieve the HTML of a page using the following ajax request: $.ajax({ type: 'GET', dataType:"jsonp", url: link, success: function(response){console.log(response)}, ...

Create a surplus of information

I'm currently working on a project where I need to replicate all the entries multiple times and then have them spin and gradually land on a color. However, I'm encountering an issue with duplicating the colors without increasing the width. How ca ...

A div element springs forth into a new window and seamlessly transitions back to its original position with fresh content

Most of us are familiar with Gmail chat, where you can pop out the chat window into a new window with its content, and then pop it back in to its original position. However, I encountered an issue while working on replicating this functionality. While I w ...

Arranging JSON information based on category

I am currently populating an HTML table with data retrieved from a JSON file. It currently displays all the data in the order it appears in the JSON file, but I would like to organize it into different tables based on the "group" category in the file such ...

Seeking assistance in understanding how to validate images in Javascript code with the use of Selenium WebDriver. Any t

I am looking to implement the following code to verify if the images on the webpage have loaded successfully. Would anyone be able to clarify how this javascript code actually confirms whether the images are loaded or not? ArrayList<WebElement> imgE ...

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

testing latency of pymongo group operations

Hey there! I've run into a problem while using pymongo==2.1.1 in python2.7 with mongo 2.4.8 I've searched for a solution on Google and Stack Overflow, but no luck. What could be causing this issue? Here's the function in question: from ...

Struggling to reset the jscrollpane scroller

When using jscrollpane in my horizontal division to enable scrolling, I encounter an issue when loading data with ajax. The scrollbar doesn't appear until the browser width is changed. To address this, I currently utilize the following method to rein ...

Difficulties accessing MongoDb database using Node.js

Having issues when trying to read this data collection using mongoose and Node.js: I have a single JSON object within my Collection and I'm attempting to access it with the following code: materias.find().exec(function(err1,materias){ if(err ...

What is the purpose of wrapping my EventEmitter's on function when I pass/expose it?

My software interacts with various devices using different methods like serial (such as USB CDC / Virtual COM port) and TCP (like telnet). To simplify the process, I have created a higher-level interface to abstract this functionality. This way, other sect ...

Filter kendo grid by selecting multiple options from a drop-down menu in the mult

I am working with a kendo grid and an HTML drop down. When I set the drop down to single select, I can successfully filter the kendo grid based on the selected item's string value. Below is the filtering code that works for single select: $("#Locati ...

Definitions have not been declared

My coding is as follows: var data = JSON.parse(http.responseText); var weatherData = new Weather(cityName, data); weatherData.temperature = data.main.temp; updateWeather(weatherData); function Weather(cityName, data) { this.cityName = cityNa ...

Trouble with axios post request, data not reaching Django view

I am attempting my initial post request utilizing axios to a Django view that accepts both POST and GET methods. However, I am receiving an empty dictionary from the request.POST: <QueryDict: {}> [13/Aug/2022 16:44:00] "POST /users/1142606705924 ...

methods for retrieving nested JSON data from an API endpoint

My data has been exported in JSON format { "count":79, "stories":{ "23658975":{ "title":"NOMINATIVO", "description":"BUSDRAGHI PIERGIORGIO", "updated_at":"2013-06-16T18:55:56+02:00", "created_at":"2013-06-16T18:39:06+02:00", "du ...