Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]}}
        )
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
}};

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}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading