How To Use Object Relational Mapping in Node - Js - Optimize Database Interactions With Sequelize ORM
How To Use Object Relational Mapping in Node - Js - Optimize Database Interactions With Sequelize ORM
Oluwatobi
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 1/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
Databases play a vital role in the development of applications across mobile and web
platforms. Adequate knowledge of data interactions between the application structure and
the database is essential for storing relevant application data.
Knowledge of Node.js
Table of Contents
Table of Contents
What is an ORM?
Demo Project
Additional Information
What is an ORM?
Object Relational Mapping (ORM) is a database communication concept in programming
that involves the abstraction of data types as compatible object-oriented programming
variables. It simply eliminates the use of database-defined queries and storage types to
allow ease of creating databases via the programming languages.
Its use has been widely adopted in the tech space as has more advantages than
conventional database query methods. Here are some of them:
It reduces the risk of data manipulation: SQL and non-SQL injections involve inputting
malicious SQL syntaxes and queries into the database, which can compromise
database security. Having an ORM in place adds an input validation scheme feature,
and details the expected input variable syntax and processes it accordingly.
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 2/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
This feature also allows easy code portability, achieving maintenance of a single
database integration code base while changing the database without any adverse
outcome. It is highly flexible and can be used in any database of choice.
SQLAlchemy
Prisma ORM
Sequelize
ActiveRecord
TypeORM
Waterline
For this article, we’ll be streamlining our ORM use cases to a basic Node.js project linked to
a MySQL database. We’ll use the Sequelize ORM as the tool of choice.
With an average package download of 8.5 million monthly and an active development
community, Sequelize boasts robust features that seamlessly integrate databases with
backend applications. It also provides a user oriented documentation which helps guide the
user on setting up and using the tool.
Here is a link to the documentation. It also offers support for MySQL, DB2, and SQLite
Microsoft SQL server, and it offers features such as read replication, lazy loading, and
efficient database transaction properties.
Next, we’ll set up our web application and install Sequelize to connect us to a MySQL
database hosted locally.
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 3/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
Next, install the Express package – this will serve as the backend framework. You can do
this by running the npm i express command.
We’ll use a locally hosted MySQL database. To do this, we’ll install an npm package
database driver. In this case, we will be installing mysql2. Here is a link to the package
Let’s move on to configuring the connection to the database and building our demo project.
Demo Project
In this section we’ll build a simple backend server that performs Create-Read-Update-Delete
operations, with the Sequelize library serving as the connection pipeline.
In order to begin the project, we’ll have to set up the database connection for our application.
We’ll create a database connection file and set up our database credentials. You can name
the file SequelizeConfig.
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "",
DB: "sequel",
dialect: "mysql"
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 4/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
In the code above, the database credentials were specified, along with the host address. In
our case, the database is locally hosted, so localhost is the default host.
The database login details were also provided. The user here is the root, while the password
was set to an empty string. This should be tweaked to ensure database security. I also
created a defunct database named “sequel”.
The dialect refers to the type of database the user intends to use. In our case, the dialect is
MySQL. Note that this can also be replicated on a cloud hosted database with the
credentials obtained. With that, let's integrate the connection file with the application.
host: SequelCOnfig.HOST,
dialect: SequelCOnfig.dialect
});
In order to facilitate a connection to the database, the variables in the config file were
imported and initialized in the Sequelize setup file.
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
module.exports= db;
This file above imports the config file created previously and initializes the Sequelize library.
The code then fetches the database details inputted in the config file and, when executed,
creates the database.
Furthermore, the various database models which will be discussed subsequently are then
integrated with the defunct database and generates a SQL database table .
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 5/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
To get this up and running, the database file created is invoked using the sequelize.sync()
method. Any error encountered is logged and the database connection gets terminated.
db.sequelize.sync().then(() => {
}).catch(err => {
console.error(err)
})
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 6/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
Models
sequelize.define(
"user", {
firstName: {
type : Sequelize.DataTypes.STRING,
allowNull : false
},
lastName: {
type : Sequelize.DataTypes.STRING,
allowNull : false
},
email : {
type : Sequelize.DataTypes.STRING,
},
password: {
type : Sequelize.DataTypes.STRING,
allowNull : false
},
role: {
type : Sequelize.DataTypes.STRING,
allowNull : false
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 7/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
In the code above, the user model was initialized in Sequelize ORM and the field details
were specified: email, role, lastName, and password. The type of data to be received was
also specified.
It also provides an option to ensure the uniqueness of the user details, and the option to
prevent the user from leaving some fields empty via the use of allowNull = false.
On execution of the application, the Sequelize ORM creates an SQL equivalent of the model
as a data table.
Create Operation
try {
if (ifEmailExists) {
} catch (error) {
throw error;
};
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 8/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
The function above highlights the controller function for creating user entries in the Express
server.
The function is asynchronous, which allows for execution of some commands before
eventual execution. The code ensures that the user email doesn’t exist in the database
before cresting a new user.
In addition, we also ensured that each email field is unique. If the user details are entered
into the database successfully, a “successful” response is sent back to the server.
Additionally, any error encountered leads to termination of the function and the error gets
sent back to the server.
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 9/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
Read Operation
let userDets;
if (userId) {
if (!userDets) {
} else {
if (userDets.length === 0) {
The read operation fetches the desired query and sends it back to the user without
modification. The user ID, which should be unique, is used to search for a specific user. In
this scenario, we want access to all the users created in the database.
In case the requested query is not found, an appropriate error code is generated.
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 10/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
Update Operation
if (!user) {
};
The update operation aims to modify the data entered in previous operations. That is, to
update some data fields.
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 11/12
12/1/24, 11:48 AM How to Use Object Relational Mapping in Node.js – Optimize Database Interactions With Sequelize ORM
In the case of Sequelize, the update method is invoked. To succeed with this, the particular
user to be edited must be identified. The code above then generates the updated data field
and sends it as the output of a successful request.
Delete Operation
if (!user) {
await user.destroy();
return user; // Return the deleted user object (useful for confirmation)
};
The delete operation is invoked when data in the database table needs to be deleted.
Sequelize makes provision for this via the use of the destroy method. This method deletes a
specific user. When executed, a success response code is displayed.
https://www.freecodecamp.org/news/object-relational-mapping-in-nodejs-with-sequelize-orm/ 12/12