首页 > 解决方案 > 使用 bodyparser 在多行上创建 Postgres 更新

问题描述

使用 Express 和 Postgres 构建的应用程序。

我正在使用 body-parser 从表单中获取逗号分隔的值。通常,这样的查询将适用于更新我表中的一个产品:

const sqlProdOrder = 'UPDATE product_index SET product_ordered = $2 WHERE product_id = $1';

但是,现在我正在尝试使用不同的数据同时更新多行。我看到了一个previous question并得出了这个结论,但我仍然收到一个查询错误:

const sqlProdOrder = "WITH sample (product_id, product_ordered) AS ( SELECT * FROM unnest(ARRAY['$2'], ARRAY['$1'])) UPDATE product_index SET product_ordered = s.ordered FROM sample s WHERE product_id = s.id";

这是带有快递的帖子:

router.post('/order', auth.check.bind(auth), (req, res) => {
const paramsProdOrderId = [req.body.product_id, req.body.product_ordered];
db.query(sqlProdOrder, paramsProdOrderId).then((results) => {
    if (results.rowCount === 0) {
        res.redirect('/products');
        return;
    }
    res.redirect('/');
})

.catch((err) => {
    res.redirect('/error/404')
});

});

当然,使用这两个“sqlProdOrder”查询会导致我被发送到 /error/404。

我已经控制台记录了正文解析器数据,一切都很好。我真的认为“sqlProdOrder”的第二个例子会起作用。

我非常感谢您对此的帮助。我相信我需要使用 unnest,但我真的不知道如何使用它,正如您在我的示例中所看到的那样。

标签: node.jspostgresqlexpressbody-parser

解决方案


使用下面的代码,简而言之,使用第一个sqlProdOrder查询,这是调用更新查询的理想方式。

块引用

编辑:我使用 ANY 为 1 美元,因为它是一个整数数组。

router.post('/order', auth.check.bind(auth), (req, res) => {

  const { product_id, product_ordered } = req.body;

  db.query(
    'UPDATE product_index SET product_ordered = $2 WHERE product_id = ANY($1)',
    [product_id, product_ordered]
  )
    .then(results => {
      if (results.rowCount === 0) {
        res.redirect('/products');
        return;
      }
      res.redirect('/');
    })

    .catch(err => {
      res.redirect('/error/404');
    });
});

推荐阅读