Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda