Using ES6 template strings to access MongoDB object keys

I am attempting to modify an array within my collection using the following method:

 var str = "list.0.arr";
    db.collection('connect').update({_id: id}, {$push:  { `${str}`: item}}); 

While the above code works perfectly fine, it throws an error Unexpected token when written like this:

db.collection('connect').update({_id: id}, {$push:  { "list.0.arr": item}}); 

My query is, how can I make the first approach work with the object key?

Answer №1

When working with object literals in JavaScript, it's important to note that template literals cannot be used as keys directly. Instead, you should use a computed property for this purpose:

db.collection('connect').update({_id: id}, {$push: {[str]: item}}); 
//                                                  ^^^^^

For more information on using a variable for a key in a JavaScript object literal, check out this helpful resource.

Answer №2

Prior to performing the update operation, ensure that the string is used as a key in the update document:

let strKey = "list.0.arr",
    queryObject = { "_id": uniqueId },
    updateObject = { "$push": {} };
updateObject["$push"][strKey] = itemToPush;
database.collections('connect').update(queryObject, updateObject); 

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

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...

Transfer the function reference to a standalone JavaScript file for use as a callback function

In an effort to streamline my ajax calls, I have developed a JavaScript file that consolidates all of them. The code snippet below illustrates this common approach: function doAjax(doAjax_params) { var url = doAjax_params['url']; var re ...

What is the process for choosing specific fields in the query using MongoDB's Geospatial feature?

Currently, I am implementing MongoDB Geospatial functionality in conjunction with node.js and express to find the nearest streets near a specific point. My aim is to retrieve only the 'name' and 'address' fields in the result set. Howev ...

Add the html tag in front of the existing html tag

I am encountering an issue with my html template (which includes jquery, js and all necessary imports in the head section). Specifically, I am attempting to prepend new paragraphs before an existing paragraph with the id "board-page": <div class="conta ...

What are the best practices for utilizing databases with both Javascript and JSF frameworks?

I am currently following the recommendations provided by @BalusC, with additional guidance available here. (The reason I'm posting this here is because it's not related to my previous question). My goal is to retrieve data from my database and d ...

Switch the <div> depending on the dropdown option chosen

@Html.DropDownList("Category", @Model.Select(item => new SelectListItem { Value = item.Id.ToString(), Text = item.Name.ToString(), Selected = "select" == item.Id.ToString() }), new { @class = "form-control", id = "dropDownList ...

Menu with hover functionality in JQuery that functions as a standard menu even when JavaScript is disabled in the browser

Is it possible to modify this code so that the hover point links' images do not appear if the browser has JavaScript disabled? And can the links function like a regular hover point even when JavaScript is disabled? <script type="text/javascript" s ...

Shanty_Mongo teams up with Zend Framework 1.11

I am currently exploring the world of Zend Framework 1.11 and MongoDB integration. In an attempt to seamlessly connect Zend and Mongo, I have opted to utilize Shanty_Mongo as a library. However, I have encountered a roadblock in the form of this exception: ...

The result of the MongoDB bulk.execute() promise remains in limbo, unable to resolve or reject, and the bulkWriteResult is nowhere

Running MongoDB version 3.6.7 with mongoDB node.js driver version 3.1.10. I've encountered an issue with a function designed to perform a bulk unordered data insertion into the database. Although the data is successfully inserted when I call bulk.exe ...

The shared hosting PHP MongoDB driver is having trouble connecting to MongoDB Atlas

While attempting to connect to MongoDB Atlas free tier from a shared hosting using MongoDB driver 1.5.2, I encounter an error when trying to write a simple document. Can you help me identify what might be causing this issue? $manager = new MongoDB\Dr ...

What is the correct method for configuring access permissions?

I'm in the process of developing a user management system, but I keep finding myself having to check the user type for each router. router.get('/admin/settings', (req, res) => { if(admin) { //Proceed. } } router.get(&apo ...

Event for terminating a Cordova application

We are looking for a way to send a notification to the user's device when our app is closed rather than just paused. On iOS, this occurs when you double click the home button and swipe up on the app, while on Android it happens when you press the Men ...

AngularJS is experiencing issues with the sorting filter 'orderBy'

I am experiencing an issue with sorting a table list that has three columns. I have implemented the ability to sort all columns in ascending and descending order. However, when I click on the -Tag to initiate the sorting process, I encounter the following ...

I am in need of a blank selection option using an md-select element, and I specifically do not want it to be

I'm currently utilizing Angular Material with md-select and I am in need of creating a blank option that, when selected, results in no value being displayed in the select dropdown. If this blank option is set as required, I would like it to return fal ...

Internet Explorer causing problems with JQuery

I encountered an error with the following code snippet: jQuery.post('/user/result/generate',{ 'id': getHidden() }, function(html) { $('#result').html(html); }); The error message is: ...

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

What is the best way to tally up all the image tags contained in an HTML string?

After generating some HTML using a WYSIWYG editor, I need to work with it in my Angular project. Imagine I have the following stringified HTML: '<p>Here is some text with an image</p><br><img src="data:base64;{ a base64 stri ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

Creating Interactive Image Thumbnails with jQuery Dialog in ASP.NET MVC 4

Trying to implement a small functionality using jQuery and ASP.NET MVC 4, I encountered a problem. The issue lies with a list of thumbnails that represent products in my application: <ul class="thumbnails"> @foreach (var thumbnail i ...

I'm getting an error message that says THREE is not recognized. How can I resolve this issue

Currently, I am diving into the world of Three.js and encountering a persistent error that has been quite challenging to resolve. Despite my efforts in exploring various solutions, the error remains unresolved. I have ensured that the Three.js library is ...