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

271
Vistas
How to update only one column and avoid NULL values for others in node-postgres?

Right now, in my API if I only want to update one value like email, other values become NULL and I have to rewrite all the other stuff as well just to update one thing.

The JSON object is this:

{
    "username": "batman"
}

This will be the result:

{
    "message": "User Updated Successfully!",
    "user": {
        "user_id": 44,
        "name": null,
        "username": "batman",
        "email": null,
        "phone": null,
        "website": null
    }
}

So, this obligates me to write the whole JSON object so that other values don't update to NULL:

{
    "name": "batman",
    "username": "batman",
    "email": "batman@cave.com",
    "phone": "0123456789",
    "website": "batman.com"
}

This is the callback function for the PUT request:

const updateUser = async (req, res) => {
  const id = parseInt(req.params.id);
  const { name, username, email, phone, website } = req.body;
  try {
    const update = await db.query("UPDATE users SET name = $1, username = $2, email = $3, phone = $4, website = $5 WHERE user_id = $6 RETURNING *", [
      name,
      username,
      email,
      phone,
      website,
      id,
    ]);
    res
      .status(200)
      .json({ message: "User Updated Successfully!", user: update.rows[0] });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Something Went Wrong!" });
  }
};

Is there any way to update only one value without the others updating to NULL?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I managed to solve my problem by following this article's instruction:

Conditional update in PostgreSQL

UPDATE users 
    SET 
        name = COALESCE (NULLIF($1, ''), name),
        username = COALESCE (NULLIF($2, ''), username),
        email = COALESCE (NULLIF($3, ''), email),
        phone = COALESCE (NULLIF($4, ''), phone),
        website = COALESCE (NULLIF($5, ''),
        website) WHERE user_id = $6
RETURNING *;
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