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): |
|
|
|
Interactive shell (client): |
|
|
|
Installing Node.js client library: |
|
|
|
Importing client library in Node.js: |
|
|
|
Connecting to the Database: |
|
|
|
Performing a query: |
|
|
|
Client library documentation: |
|
This chapter’s chapter08_sql_raw
and chapter08_docstore_raw
projects contain examples which use the client libraries to read from a database.