Addressing the problem of refactoring in JavaScript when associating arguments with keys in MongoDB

I am facing a dilemma with two functions that are almost identical except for the value being set as indicated:

            function extracted_start(details, txt) {
                return FutureTasks.upsert({
                        number: details.number,
                        start_date: details.start_date,
                        end_date: details.end_date
                    }, {
                        $set: {
                            access_rights: txt,
                        }
                    },
                );
            }

            function extracted_end(details, txt) {
                return FutureTasks.upsert({
                        number: details.number,
                        start_date: details.start_date,
                        end_date: details.end_date
                    }, {
                        $set: {
                            returned_status: txt,
                        }
                    },
                );
            }

When attempting to refactor using a generic function as shown below, I encounter an issue with 'key' not being recognized. What could be the problem?

            function extracted_generic(details, key, txt) {
                return FutureTasks.upsert({
                        number: details.number,
                        start_date: details.start_date,
                        end_date: details.end_date
                    }, {
                        $set: {
                            key: txt,
                        }
                    },
                );
            }

Answer №1

Instead of using the key as a literal value, you need to assign it as a variable within an object. This can be achieved by creating an object and manually adding the key-value pair with obj[key] = txt. (As a side note, there is a misspelling of 'generic' in your function name.)

function extracted_generic(details, key, txt) {
  var obj = {},
      obj[key] = txt;

  return FutureTasks.upsert({
    number: details.number,
    start_date: details.start_date,
    end_date: details.end_date,
  }, {
    $set: obj
  });
}

Answer №2

When the variable key is being considered as the actual word "key", it is best to create your object first and then utilize it in this way:

let newObj = {};
newObj[key] = text;
..
..
$set: newObj

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

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...

Searching with $in operator now supports case insensitive queries

What is the optimal way to search a column within a MongoDB collection using the `$in` method with an array of elements for searching while also implementing case-insensitive matching? ...

HTML5 allows users to choose data from a list using a ComboBox and submit the 3-digit code

I'm looking to enhance my form by including an input box where users can select airports, similar to the functionality on this website (). When typing in the Destination Input, I want users to see a list of possible values with detailed suggestions su ...

Form validation on the client side: A way to halt form submission

I have a form with several textboxes. The unobtrusive jquery validation is functioning properly and correctly turns the boxes red when invalid values are entered. However, I've noticed that when I click to submit the form, it gets posted back to the s ...

Loading images in advance before webpage loads

Welcome friends! This is my first time asking a question here, so I hope I'm doing it right :) I'm looking to preload 3 images before the webpage fully loads so that they all appear simultaneously. Currently, the images load one after another and ...

Using the ternary operator to insert elements from one JavaScript array into another array

In my React form, I am dealing with an array of objects that represent different fields. Depending on a boolean state, I need to dynamically change the sequence of fields displayed. While I have no trouble inserting a single object into the array, I am s ...

Ways to transform epoch timestamp to present timestamp?

Is there a way to accurately convert an epoch timestamp in milliseconds to the current timestamp in milliseconds? My Attempt: var currentTime = (resp.timestamp * 1000) + 1980000000; resp.timestamp represents the epoch timestamp I attempted to add 5 ho ...

Placing a cookie using nookies within the Next.js API directory

I'm currently facing an issue while trying to use the nookies npm package to set a cookie within the Next.js api folder. I've successfully set up a cookie using the same code with nookies before, but for some reason, it's not working in this ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Unending Mongoose request delay

Situation: Using Mongoose v4.7.6 Working with MongoDB v3.2.11 Currently facing issues regarding database errors in my software. Encountering a problem where mongoose requests hang when the database is disconnected and only resume once reconnected. Th ...

Utilizing D3 to fetch geographic data in the form of a TopoJSON file for U.S. counties

After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet: navigator.geolocation.getCurrentPosition(function(position) { let coordinates: [number, number] = [p ...

What steps can I take to resolve the "SyntaxError: Unexpected token '?' " issue when trying to connect MongoDB with Node.js?

I am currently utilizing mongodb in conjunction with nodejs. I have set up the server and established the connection to the database. However, I am encountering an issue. Server.js file const http = require('http'); require("./config/dbCon ...

When you add new objects to VueJS Store, they are simply substituted for the existing objects

Currently, I am encountering an issue with the code snippet below that is used to insert a new object into the 'items' array. The problem lies in the fact that whenever a new object is added, it ends up replacing the content of the previously add ...

storing data in a nested child object within an array

I am attempting to include variables into the existing JSON data that is received from an API whenever a user clicks on the add button. However, I encountered this error message: Cannot find a differ supporting object '[object Object]' of type & ...

Tips for identifying a scroll down gesture on a touch device with jQuery

I have a method for infinite scroll that is triggered like this: $(window).on('scroll resize load', function() { // execute the infinite scroll method }); It is triggered by these events: scroll resize load However, it does not seem to ...

Adjust the size of an input field in jquery or javascript based on user input

Ensure that an input text box can only contain a maximum of 13 numbers, but if the user enters a 14th number as a decimal point, then allow up to 16 numbers. HTML: <input type="text" maxlength="15" onkeyup="checkCurrency(this)"/> Script: func ...

Insert_many in mongoDB can take in a list of dictionaries as input, whereas update_many does not have

I am encountering an issue while attempting to update a mongoDB collection with the use of update_many. I have a list of dictionaries that I want to insert into this collection. Although insert_many() works fine for inserting the list of dictionaries, I fa ...

Implementing a "Click to view additional comments" feature using PHP and AJAX

I've been working on setting up a video commenting system, but I'm stuck on getting my "load more" button to function properly. Despite checking my PHP script and finding no errors, nothing seems to be happening when I click the button. As someon ...

Starting data initialization using a property object within a Vue component

I am encountering an issue with two Vue components, EventTask and EventCard. Within EventTask, there is a currentEvent object in the data section, which I pass as a prop to EventCard using the following code snippet: <event-card :current-event="cur ...