Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda