Nikolius Lau
Nikolius Lau

Reputation: 673

nodejs postgres query return undefined after transaction query

I am having problem in one of my api using express on nodejs when that connected to postgres db. here is sample of my code

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

the updatedProduct variable is always returning undefined, anyone having a solution for this?

Upvotes: 2

Views: 2354

Answers (1)

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

The query returns an object with property rows, you have to use rows variable in object destructuring.

Example:

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

Upvotes: 1

Related Questions