Home > Software design >  How to Iterate through and Update Key Value Pairs through Patch Request on MongoDB
How to Iterate through and Update Key Value Pairs through Patch Request on MongoDB

Time:03-22

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

CodePudding user response:

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: "[email protected]"
}};

for(let key in keys) {
  console.log({key: req.body[key]}); // logs {key: CobaltGecko}, {key: [email protected]}
}

for(let key in keys) {
  console.log({[key]: req.body[key]}); // logs {name: CobaltGecko}, {email: [email protected]}
}
  • Related