从 Update 方法正确返回 API 响应。 Postgres 数据库 pg-promise Node.js

Returning API response correctly from Update method. Postgres db pg-promise Node.js

我刚开始构建 API,node.js,postgres,所以这可能是一个有点幼稚的问题.. 我注意到,当我调用 update 方法但未找到任何记录时,该方法会抛出一个错误,我期待一个空结果,我会在其中发送 404 响应。我只是想知道这(从错误返回响应)是否被认为是不好的做法,如果我不应该只执行两个查询,第一个检查记录是否存在,第二个更新它。 这是我的更新方法

exports.updateProductById = async (req, res) => {
  const productId = parseInt(req.params.id);
  const { productName, quantity, price, city, region, country } = req.body;



  await db.one({
    name: 'update-product',
    text: 'UPDATE products SET productName = , quantity = , price = , city = , region = , country =  WHERE productId =  RETURNING productId, productName, quantity, price, city, region, country',
    values: [productName, quantity, price, city, region, country, productId]
  })
    .then(result => {
      console.log('update-product:', result);
      if (result != null) {
        res.status(200).send({
          message: 'Product Updated Successfully!',
          data: result
        });
      }
      else {
        // not called
        res.status(404).send({
          error: 'Product not found.'
        });
      }
    })
    .catch(error => {
      console.log('update-product error:', error);
      // workaround
      res.status(404).send({
        error: 'Product not found.'
      });
    });
};

I have noticed that when I call the update method and no record is found the method throws an error, and I was expecting a null result.

你为什么这么期待?方法 one 的文档从一开始就清楚地告诉您:

Executes a query that expects exactly 1 row to be returned. When 0 or more than 1 rows are returned, the method rejects.

如果你想要null没有记录返回,有方法oneOrNone