EN
Node.js - PostgreSQL Update query
0 points
In this article, we would like to show you how to make an SQL UPDATE query in Node.js.
Note: at the end of this article you can find database preparation SQL queries.
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'postgres',
6
database: 'database_name',
7
password: 'password',
8
port: 5432,
9
});
10
11
const updateUser = async (userName, userRole, userId) => {
12
const query = `UPDATE "users"
13
SET "name" = $1, "role" = $2
14
WHERE "id" = $3`;
15
try {
16
await client.connect(); // gets connection
17
await client.query(query, [userName, userRole, userId]); // sends queries
18
return true;
19
} catch (error) {
20
console.error(error.stack);
21
return false;
22
} finally {
23
await client.end(); // closes connection
24
}
25
};
26
27
updateUser('Christopher', 'admin', '2').then(result => { // userName, userRole, userId
28
if (result) {
29
console.log('User updated');
30
}
31
});
Before:
xxxxxxxxxx
1
[
2
{ id: 1, name: 'John', role: 'admin' },
3
{ id: 2, name: 'Chris', role: 'moderator' },
4
{ id: 3, name: 'Kate', role: 'user' },
5
{ id: 4, name: 'Denis', role: 'moderator' }
6
]
After:
xxxxxxxxxx
1
[
2
{ id: 1, name: 'John', role: 'admin' },
3
{ id: 2, name: 'Christopher', role: 'admin' },
4
{ id: 3, name: 'Kate', role: 'user' },
5
{ id: 4, name: 'Denis', role: 'moderator' }
6
]
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(100) NOT NULL,
4
"role" VARCHAR(15) NOT NULL,
5
PRIMARY KEY ("id")
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
("name", "role")
3
VALUES
4
('John', 'admin'),
5
('Chris', 'moderator'),
6
('Kate', 'user'),
7
('Denis', 'moderator');