node.js - 使用 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,但我真的不知道如何使用它,正如您在我的示例中所看到的那样。
解决方案
使用下面的代码,简而言之,使用第一个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');
});
});
推荐阅读
- c++ - 如何获取指向 std::array 内容的 C 指针?
- python - 如何处理格式化可能是 f 字符串的常规字符串 [C0209]
- javascript - JavaScript - MutationObserver(“无法在'MutationObserver'上执行'observe':参数1不是'Node'类型”)
- python - 验证 Google API 帐户时代码未创建访问令牌
- php - 运行 .php 文件的 Cron 作业失败
- postgresql - 如何根据另一个表的点中定义的数据创建 Postgres 表?
- javascript - 从页面中删除所有内容并将其替换为统一游戏 onclick
- javascript - Can't get the images from an API to show up
- ssis - SSIS - 需要代理身份验证 SQL Server
- javascript - vue顺序执行