Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
How to Iterate through and Update Key Value Pairs through Patch Request on MongoDB

I am trying to set up a patch request to the endpoint "/api/user?username=idHere". It is intended to take a json body, and be capable of reading every key value pair and updating the user in MongoDB with those new values. Right now though, the line "{$set: {key: req.body[key]}}" is interpreted literally, and it's trying to set the actual word "key" to a value instead of the key in the request body. How can I go about accomplishing this goal correctly? My current code for attempting this is below.

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]}}
        )
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

JavaScript allows you to use parameterized key names with square braces.

// Will use the value of the "key" variable for the key
{ [key]: req.body[key] }

// Will use the word "key" for the key
{ key: req.body[key] }

For example,

const req = { body: {
  name: "CobaltGecko",
  email: "cobalt@gmail.com"
}};
const keys = Object.keys(req.body);

for(let key in keys) {
  console.log({key: req.body[key]}); // logs {key: CobaltGecko}, {key: cobalt@gmail.com}
}

for(let key in keys) {
  console.log({[key]: req.body[key]}); // logs {name: CobaltGecko}, {email: cobalt@gmail.com}
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!