JavaScript Value is used to declare keys in MongoDB

I'm trying to assign a value as the key of an array in MongoDB.

The value I want to use is stored in a variable:

var value = "arrayKey" and my goal is to update a MongoDB collection by setting this value as a key.

collection.update(
    {
        "schraenke.name": schrank.name
    }, 
    {
        $push: {
            value: {
                "test": test
            },
        }
    }
});

However, when I attempt this, the key being created is "value" instead of "arrayKey".

Answer №1

The reason for this behavior is that keys are treated as literal when written in a certain way. To work around this, you can first create the object and then use bracket notation to incorporate dynamic keys. Here's an example:

var key = "dynamicKey";
var obj  = {};

obj[key] = { "value": someValue };

database.update({"criteria.name": criteriaName }, {$set: obj});

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

Turn off wss for ASP.NET Core Hot Reload functionality

Currently, I am utilizing ASP.NET Core's hot reload functionality. It attempts to establish connections with two websockets: ws and wss. The ws connection is successful and enables hot reload to function properly. However, since my local development ...

The x-axis is fixed and displays a datetime type column

My chart's column type is set to datetime but it is displaying unnecessary dates with large spaces in between on the x-axis, and the size of the columns has been reduced to almost invisible. [screen shot 1]: https://i.sstatic.net/oXpUT.png If I cha ...

Transferring information between Flask and JS using AJAX for a Chrome extension

I'm experimenting with AJAX calls to establish communication between my Javascript frontend in a chrome extension and the Flask API where I intend to utilize my Machine Learning algorithms. content.js console.log("Let's get this application ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

Log4j MongoDB experiencing prolonged delay in timeout after 30000ms

I have set up Log4j2 to log information to my Mongo Atlas cluster (version 4.4.8). The configuration appears to be correct (using the connection string provided by Atlas), and the console logs indicate that the connection to MongoDB is successful, with th ...

Tips for updating saved data in MongoDB with the help of Express

Is it possible to update a MongoDB document using Express as the backend? Check out the backend API provided below: app.post("/update",(req,res)=>{ const id=req.body.id; console.log(id); contact.updateOne({'_id':i ...

The YUI framework is skilled at creating new lines while erasing the old ones

I am looking to create a line when the mouse is clicked, and remove the previously drawn line. View the code on jsfiddle.net at this link. While my current code successfully draws a line when the mouse is clicked, it does not remove the previous line. I n ...

Leveraging Ninject for MongoDB: Efficient Dependency Resolution for Repository

It seems like I have hit a roadblock in understanding how Ninject operates across different assemblies. I have an asp.net mvc website that is referencing a Core.dll which houses my domain objects, repository, and some services. One of my domain objects has ...

Creating a POST request in Rails 3

Is there a way to integrate web services in Rails 3 by sending POST parameters to an external URL? Typically, I utilize a command line method like the one below for posting: curl -X POST -u "v10REVkw:XuCqIhyCw" \ -H "Content-Type: application/json" & ...

Understanding the Parameters for discord.js Slash Commands

I am currently working on a calculation that involves using parameters input through a slash command. While entering the parameters works without any issues, I am facing difficulty in retrieving them. The current code is resulting in an error TypeError: ...

AngularJS dropdown not reflecting changes when using ng-selected

While working with AngularJS, I have encountered an issue where the first child of the select element remains empty despite my efforts to populate it. Below is the HTML code snippet: <select id="connectTV" aria-label="How many Dish TVs" ng-model="conn ...

Why does the array format of the values saved in app.locals seem to disappear when they are accessed in the view?

I have created a date values array and stored it in an app.locals variable using the code snippet below: prepDataList.forEach(function(item){ var str = item.createdAtDate.toDateString(); //str = str.substring(4, 10); labelsArray.push(str); counts ...

Issue with Refreshing onRowAdd in React Material Table

I am currently using Material Table to display my table data. However, when I use the onRowAdd function to add a new row, the page does not refresh properly. Instead, it reloads and gets stuck, requiring me to manually refresh again. newData => ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

Exploring the World of Images with Javascript

I'm currently working on creating a slideshow using HTML and JavaScript. My goal is to have the image change each time I press a button that I've established (see code below). After reviewing my code multiple times, I still can't figure out ...

Tips for selecting a specific input field in a ReactJS component with multiple inputs

I am currently developing a ReactJS application where I have implemented a component responsible for generating an HTML table. Within this component, I utilize Map to create rows using a child component. These rows contain multiple input fields that users ...

Explore the world of threejs with a sphere adorned with cube bumps

Currently, I am navigating through the internet in search of a solution for my problem. The example I came across is quite impressive, take a look: . My dilemma lies in converting these squares into CSS cubes while ensuring that they do not get cut off by ...

What could be preventing the Python server from successfully receiving and sending messages?

I have developed a chatbot using Python and now I want to integrate it into my React website. However, I am encountering an error while trying to send data from localhost:/3000 to the Python server at localhost:/5000: Could not proxy request /js/jquery-1. ...

NodeJS produces identical outcomes for distinct requests

RESOLVED THANKS TO @Patrick Evans I am currently working on a personal web project and could use some assistance. In my website, users are prompted to upload a photo of their face. When the user clicks the "upload" button, the photo is sent with a request ...

Ways to trigger a PHP function after a successful AJAX query

I have incorporated AJAX into my project, as shown in the code below: $.ajax({ type: 'POST', data: ..., success: function(data) {<?php calc(); ?>}, error: function(jqXhr, textSt ...