A guide on how to cycle through and modify key-value pairs using a Patch Request in MongoDB

I am working on configuring a patch request for the endpoint "/api/user?username=idHere". This patch request should accept a JSON body and update the user in MongoDB with the new key-value pairs. Currently, the line "{$set: {key: req.body[key]}}" is being interpreted literally, trying to set the word "key" as the key instead of the actual key from the request body. How can I achieve this goal correctly? Below is my current code attempting this.

const updateUser = (req, res) => {
    const db = mongoConnection.getDb();
    const keys = Object.keys(req.body);

    for (key in keys) {
        db.collection('users').updateOne(
            {username: req.query.username},
            {$set: {key: req.body[key]}}
        )
    }
}

Answer №1

Using JavaScript, you have the ability to utilize parameterized key names enclosed in square brackets.

// The key variable's value will be used as the key
{ [key]: req.body[key] }

// The key will simply be "key"
{ key: req.body[key] }

For instance,

const req = { body: {
  name: "CobaltGecko",
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4f434e4d40586c4b414d4540024f4341">[email protected]</a>"
}};
const keys = Object.keys(req.body);

for(let key in keys) {
  console.log({key: req.body[key]}); // outputs {key: CobaltGecko}, {key: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04676b66656870446369656d682a676b69">[email protected]</a>}
}

for(let key in keys) {
  console.log({[key]: req.body[key]}); // displays {name: CobaltGecko}, {email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfdcd0ddded3cbffd8d2ded6d391dcd0d2">[email protected]</a>}
}

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

One way to incorporate if / else if statements into a function within a Class component is by using conditional logic in React alongside Node and Express

I'm looking to refactor my code and extract the if/else if statements for error handling out of the component. How can I export this logic to another file and then import it back into my main component? Here's an example of the code: // PASSWOR ...

Refresh and append values to multiple select2 fields following an ajax request

I recently encountered an issue where I needed to add values to a select2 (multiple select) field after making an ajax call. In my quest for a solution, I came across this helpful question on Stack Overflow: Dynamically add item to jQuery Select2 control ...

What is the technique for showcasing a collection of <v-img> elements with the v-for directive?

Hey there, hope you're all doing well. I'm curious about how to use the v-for method in Vue js to display a list of images. For example, if I have code that looks like this: <v-flex> <h4>{{$translate('bz_doc_path') ...

How can I send a cookie to the front end across different domains using Firebase Cloud HTTP functions?

I encountered a challenge while trying to set up cross-domain authentication for my domain and sub-domains. Currently, my backend operates on firebase cloud functions with a domain like https://my-region-firebase-project-id.cloudfunctions.net. My attempt ...

I need to retrieve the Home Page data in React Native based on the email address of the logged-in user

After logging into my project with an email and password, I need to fetch Home Page data based on the logged-in email. The API will provide response data specific to that user. In useState(), I have set a static email which needs to be changed dynamicall ...

What is the best way to ensure the constant rotation speed of this simple cube demo?

Currently delving into the world of Three.js. I'm curious about how to make the cube in this demo rotate at a consistent speed rather than depending on mouse interactions. Any tips on achieving this? ...

Menu changes when hovering

I want to create an effect where hovering over the .hoverarea class will toggle the visibility of .sociallink1, .sociallink2, and so on, with a drover effect. However, my code isn't working as expected. Additionally, an extra margin is automatically ...

Can XMLHttpRequest be exploited for XSS attacks?

Can cross-site scripting be achieved using an XMLHttpRequest as a post method? For instance, in a chatroom where users can enter text. Normally, inserting scripts like <script>alert("test")</script> would be blocked. However, you could write a ...

Import reactjs modules without the need for Browserify, Webpack, or Babel

I am attempting to set up a TypeScript HTML application in Visual Studio. My goal is to incorporate reactjs v0.14.7 without relying on tools like Browserify. But, how can I utilize the react-dom module in this scenario? Let's set aside TypeScript fo ...

Is there a way to conceal the contents of a page until all the images have finished loading?

I'm currently working on improving the performance of a website that is loading very slowly. I have already reorganized, compressed and minified the JavaScript and CSS files, but the main issue seems to be with the images. The site contains large imag ...

Creating a banner image that scrolls while maintaining a fixed size

I'm looking to add a banner image with a scrolling effect as users navigate down the page, but I'm not sure what this technique is called. An example of what I'm trying to achieve can be seen on this site. As the user scrolls down, the res ...

Is it possible to implement a single OrbitControls with two cameras in ThreeJS?

Is there a way to link the OrbitControls of two canvases on the same page? For example, if the user zooms in on one canvas, I want the other canvas to also zoom in simultaneously. How could I achieve this synchronization between multiple canvases? ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

Creating a dynamic multi-choice dropdown list with Django and Vue.js

I have been attempting to implement the Vue.js multiselect component from the following link: However, I am encountering an issue where instead of the expected multiselect dropdown, the output is not as desired and looks like this: https://i.sstatic.net/ ...

Await that's locked within a solo asynchronous function

async function submitForm(e){ e.preventDefault() console.log(e.target) try { const response = await axios.post('/api/<PATH>', {username, password}); console.log(response.data); const token = response.data.token if (t ...

Will there ever be a possibility in the future to compile from D 2.0 to Javascript?

An experienced C++ programmer (that's me) is venturing into other programming languages and considering the value of learning more about D 2.0. The clean, fresh rewrite of D has caught my eye with its pragmatic and wise choices. Now, I'm eager to ...

Adjust the Angular menu-bar directly from the content-script of a Chrome Extension

The project I've been working on involves creating an extension specifically for Google Chrome to enhance my school's online learning platform. This website, which is not managed by the school itself, utilizes Angular for its front-end design. W ...

Convert the button element to an image

Can someone please explain how to dynamically change a button element into an image using javascript when it is clicked? For instance, changing a "Submit" button into an image of a check mark. ...

Experiencing issues with connecting to jQuery in an external JavaScript file

My jQuery formatting in the HTML file looks like this: <!doctype html> <html lang="en"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script> </head> < ...

How can I pass a value as an attribute from an Angular template to a directive?

Here's a directive I'm working with: <g-map-locations center={{myLocation}} zoom="4" id="map" class="map"></g-map-locations> The zoom parameter is used in Angular to set the zoom level for a Google Map: attrs.zoom = zoom setMapOpti ...