node.js - nodejs postgres查询在事务查询后返回未定义
问题描述
当连接到 postgres db 时,我的一个 api 在 nodejs 上使用 express 时遇到问题。这是我的代码示例
const Router = require('express-promise-router');
const pool = require('../db/pool');
const router = new Router();
module.exports = router;
router.put('/:id', async (req,res) => {
const client = await pool.connect();
try {
//await client.query('BEGIN');
const queryText = "UPDATE product SET categoryid=$1, ownerid=$2, title=$3, description=$4, price=$5, stockquantity=$6 WHERE id=$7";
const result = await client.query(queryText, [req.body.categoryid,req.body.ownerid,req.body.title,req.body.description,req.body.price,req.body.stockquantity,req.params.id]);
//await client.query('COMMIT');
const { updatedProduct } = await pool.query("SELECT * FROM product WHERE id = $1 LIMIT 1", [req.params.id]);
res.json({
success: true,
message: "Product updated",
updatedProduct: updatedProduct
});
} catch (error) {
await client.query('ROLLBACK');
res.status(500).json({
success: false,
message: error.message
});
} finally {
client.release()
}
});
updatedProduct变量总是返回未定义,有人对此有解决方案吗?
解决方案
query
返回一个带有属性的对象,rows
你必须rows
在对象解构中使用变量。
例子:
const Router = require('express-promise-router');
const pool = require('../db/pool');
const router = new Router();
module.exports = router;
router.put('/:id', async (req,res) => {
const client = await pool.connect();
try {
//await client.query('BEGIN');
const queryText = "UPDATE product SET categoryid=$1, ownerid=$2, title=$3, description=$4, price=$5, stockquantity=$6 WHERE id=$7";
const result = await client.query(queryText, [req.body.categoryid,req.body.ownerid,req.body.title,req.body.description,req.body.price,req.body.stockquantity,req.params.id]);
//await client.query('COMMIT');
const { rows } = await pool.query("SELECT * FROM product WHERE id = $1 LIMIT 1", [req.params.id]);
res.json({
success: true,
message: "Product updated",
updatedProduct: rows
});
} catch (error) {
await client.query('ROLLBACK');
res.status(500).json({
success: false,
message: error.message
});
} finally {
client.release()
}
});
推荐阅读
- r - 无法同时使用 geom_boxplot、geom_text 和 geom_hline 自定义 ggplot2 中的颜色和其他功能
- excel - Excel VBA将打印区域附加为PDF
- php - 在 Woocommerce 中设置购物车商品价格后重新计算总计
- android - CMAKE_CURRENT_BINARY_DIR 的 Gradle 模拟是什么?
- python - 通过服务器读取数据时,python f.read() 和 f.seek() 很慢
- java - 如何从 Java URLConnection getContent 获取数据到字符串
- asp.net-mvc - Azure API 网关和 Web 应用程序 - 如何提供 CSS、JS 和图像?
- python - 单击 - 基于其他选项的提示的动态默认值
- android - Activity 与 AppCompatActivity:UI 的区别
- visual-studio - 使用生成的符号在反编译源中的断点处发出“未加载符号”通知