如何只更新一列并避免 node-postgres 中其他列的 NULL 值?

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

现在,在我的 API 中,如果我只想更新一个值,例如 email,其他值将变为 NULL而且我还必须重写所有其他内容,只更新一件事。

JSON对象是这样的:

{
    "username": "batman"
}

这将是结果:

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

因此,这迫使我编写整个 JSON 对象,以便其他值不会更新为 NULL:

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

这是 PUT 请求的回调函数:

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 = , username = , email = , phone = , website =  WHERE user_id =  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!" });
  }
};

有没有办法只更新一个值而不更新其他值到NULL?

我按照本文的说明设法解决了我的问题:

Conditional update in PostgreSQL

UPDATE users 
    SET 
        name = COALESCE (NULLIF(, ''), name),
        username = COALESCE (NULLIF(, ''), username),
        email = COALESCE (NULLIF(, ''), email),
        phone = COALESCE (NULLIF(, ''), phone),
        website = COALESCE (NULLIF(, ''),
        website) WHERE user_id = 
RETURNING *;