§8.7.

Using a database from Node.js

Your Node.js code communicates to your database over a network connection, using a proprietary protocol. For Node.js applications, a client library must be installed to interface with this proprietary protocol.

The specific library you choose to install will depend on the database management system and the features you want to use. For PostgreSQL, a good choice for direct access to the database is pg. For MongoDB, the ‘official’ client library is mongodb. The npm install pg or npm install mongodb command installs the library.

The following table depicts the key steps in using and connecting to PostgreSQL and MongoDB:

PostgreSQL

MongoDB

Database management system (server):

postgres -D ./pgdb/ -k ''

mongod --dbpath ./mdb --bind_ip 127.0.0.1

Interactive shell (client):

psql -h localhost postgres

mongo

Installing Node.js client library:

npm install pg

npm install mongodb

Importing client library in Node.js:

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

const { MongoClient } = require('mongodb');

Connecting to the Database:

const pool = new Pool({
  database: 'postgres'
});
MongoClient.connect(
  'mongodb://localhost:27017',
  {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }
)

Performing a query:

pool.query({
  text: `select description, quantity
         from shopping_item
         where description = $1`,
  values: ['Chocolate bar']
})
db.collection('items')
  .find(
    {description:
      {$eq: 'Chocolate bar'}
    }
  )
  .toArray()

Client library documentation:

https://node-postgres.com/

https://docs.mongodb.com/drivers/node/

This chapter’s chapter08_sql_raw and chapter08_docstore_raw projects contain examples which use the client libraries to read from a database.