I am using the pg-promise NodeJS module. At some point, I am updating one of my database's table. I would like to know how many rows have been updated by the query, is it possible?
Below is part of my code:
var queryText = "UPDATE public.mytable SET whatever = $1 WHERE criteria1=$2 AND criteria2=$3;",
queryParam = [
value1,
value2,
value3
];
postgres.none(queryText, queryParam)
.then((value) => {
// how can I know at this point how many rows have been updated
resolve(result);
})
.catch(err => {
// it doesn't go here when zero row has been updated
reject(err);
});
Thank you!
I'm the author of pg-promise. In order to access the advanced query-result details, you need to execute the query via method result. And in your case you would access property rowCount
:
db.result(query, values, r => r.rowCount)
.then(count => {
// count = number of rows affected (updated or deleted) by the query
})
.catch(error => {
});
P.S. You do not need to use resolve(result)
inside .then
or reject(err)
inside .catch
, as all query methods of pg-promise already return promises.
UPDATE
Newer, ES7 syntax:
const {rowCount} = await db.result(query, values);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With