Node-Postgres Module

  • 1

  • 1

  • 1

Database integration with Node-Postgres.

A PostgreSQL server can handle a limited number of NodeJs client connections. The initial connection "handshake" data exchange can slow down the application.

The node-postgres (pg) library offers connection pooling through its pg-pool module. This module creates a pool of reusable connections for database query requests.

We create a new Pool instance with the credentials to connect to the database, we add SQL queries to the Node endpoints and res.rows as an array of objects.

const { Pool } = require('pg');

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'postgres',
  password: 'mrlzarate',
  port: 5432
});

app.get("/hotels", function(req, res) {
    pool.query('SELECT * FROM hotels', (error, result) => {
        res.json(result.rows);
    });
});
Database connection and SQL script row return

To implement CRUD operations in a pool.query() we use then() and catch().

chevron-rightNodeJs Insert, Delete and update with $ variables and [] SQL querieshashtag

We separate the query and insert an array of [variables] using $, based on their index.

On delete, we return the deleted query using returning.

On Update, we can send a patch request, if a key is not updated it will be NULL, and will return error if it's a not null key.

A single endpoint can chain multiple SQL queries.

We put them one after the other (the result.rows will be from the last SQL query).

Promise chaining manages asynchronous database queries. The .then() callback executes upon successful queries, granting access to the returned result. The .catch() handler manages errors from each query in the chain.

We validate the client's req.body data by res.status(400).

chevron-rightPostgre database query data validationhashtag

We use an additional pool.query() to check if any of the req.body data is repeated.

To Select Join reference tables we need additional conditions.

chevron-rightPostgreSQL rules for reference foreign keyshashtag

A foreign key is a key that references a primary key in another table.

PostgreSQL maintains referential integrity between tables. It will prevent the deletion of a primary key if it's still referenced by a foreign key, ensuring that foreign keys are deleted first.

Select Inner Join on NodeJs Postman Response

1

Last updated