Performing Database Operations on PostgreSQL Database Using Node.js and Sequelize Object Relational Mapping (ORM)
In this article, we will implement the database operations on PostgreSQL using Node.js and Sequelize ORM. PostgreSQL is an Open-Source, powerful object-relational database system. This database supports various features. The detailed features of this database can be read from this link.
This article is written for the audience those have basic knowledge of Node.js and Express.
What is Object-Relational Mapping (ORM)?
ORM is a technique of mapping the data schema from the database with the Object-Oriented representation in incompatible systems. The application that needs to connect to the database for performing various database operations, can use these objects to perform read/write operations instead of using typical database syntax like select, insert, update, delete queries. Various server-side technologies like JAVA, .NET, .NET Cors use various ORM frameworks like Hibernate, EntityFramework, etc. to map with database schemas (table) and perform read/write operations. While using Node.js on the server-side, we can make use of Sequelize ORM to work with database read/write operations.
What is Sequelize?
Sequelize is a promise-based Node.,js ORM which we can use for MySQL, PostgreSQL, MariaDB, Microsoft SQL Server, etc. for performing database operations. Sequelize supports database-first and code-first approaches. In the database-first approach, the JavaScript Models are generated based on database tables and in the code-first approach, database tables are generated from JavaScript Models. More information about Sequelize can be read from this link.
Let's create a database using PostgreSQL
In the beginning, I have already written that we will be using PostgreSQL for database creation. PostgreSQL can be downloaded from this link.
To create a database and tables, I have created a new user in PostgreSQL using the script shown in listing 1. This script will create a user of the name myuser with a password as P@ssw01rd. This user has the privilege of creating a database.
Listing 1: The Script to create user
Create a database of name Business and table of name Department by connecting to the PostgreSQL using the Username created using the script provided in listing 1. The script for creating the database and table is provided in listing 2
Listing 2: The Database and Table creation script
We have created a Business database and the Department table in it.
Creating Node.js and Sequelize application
Step 1: Create a folder of name nodeorm on the machine and open this folder in Visual Studio Code (VSCode). Open the Command Prompt (or Terminal window if using Linux or MacOS) and navigate to the nodeorm folder.
Step 2: This application uses Express for creating REST APIs to accept data from the client. So, let's install packages in the application by running the following command from the command prompt
npm install -g pg pg-hstore sequelize sequelize-auto sequelize-cli
npm install --save express pg pg-hstore sequelize sequelize-auto sequelize-cli
Step 3: To generate JavaScript Models from the database so that the Node.js application can use it, run the following command from the command prompt
The sequelize-auto command accepts the following switches
- h: the host machine where the database is running
- d: the database name
- u: user name
- x: password
- p: The port (Note: PostgreSQL rung default on port 5432, but since I have multiple PostgreSQL instances I have used port 5433)
- dialect: The Database provider, currently we are using Postgres
- o: the output path in the project where JavaScript Model files will be created.
- t: table (or tables) those will be used to generate JavaScript Model classes
- l esm: This switch is used to generate ES 6 JavaScript module files
- findAll(), to read all records from the table
- create(), to create new record
- update(), to update record
- destroy(), to delete the record
In, the code shown in Listing 6, contains various methods. But, one common code statement in each method is as follows
await sequelize.sync({force:false});
This mans that, sequelize will establish onnection to database and then will overwrite tables in database, the {force:false}, will make sure that, tables will not be overwritten. One more important feture of the DepartmentDataAccess class is tht all methods ate asynchronous and each method accepts request and resonse object. The reason behind the asyc methods is that all these methods are performing awaitable CRUD operations using sequelize object and department model. The request and response object will be passed to these methods using express Http pipeline which we will be crating in forthcomming steps. The request object will be used to read posted data by the client application and also header parameters. We will be using the posted values from the requestobjct to create new record and update an existing record. Once the database CRUD operations are successfully completed, response object will be used to return this data. The DepartmentDataAccess class is exported as a Node.js ES 6 module so that it will be imported by other module in the application.
Step 5: In the project add a new file and name it as server.js. In this filw we will use the Express module to create REST API. We will be using Http methods of the express object to create REST Endpoints. These endpoints will invokes methds from DepartmentDataAccess class so that values posted by the client to REST endpoints will be passed to these methods. The code of the REST API endpoints is showin in listing 6
Listing 6: The REST APIs code
We have configured the 9091 port for REST Endpoints.
To run the application, run the following command from the command prompt
node server.js
This command will expose the REST Endpoints on port 9091.
You can test the application using browser by enter address as http://localhost:9091/api/departments. The result will be as shown in figure 1
Figure 1: The result
Likewise, using Postmon, Advanced REST Client (ARC) or by creating your client application, you can test POST, PUT and DELETE requests.
The code for this article is available on this link.
Conclusion: The Sequelize provides great feature for using ORM in Node.js to make it as first class technology for development of Data Centric Applications using JavaScript.