首页 > 解决方案 > 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变量总是返回未定义,有人对此有解决方案吗

标签: node.jspostgresqlexpress

解决方案


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()
    }
});

推荐阅读