In this post, we will know how to use sequelize with node express and mysql step by step.
What is sequelize ?
Sequelize.js is an ORM (Object/Relational Mapper) which provides easy access to MySQL, MariaDB, SQLite or PostgreSQL databases by mapping database entries to objects and vice versa. It has very powerful migrations mechanism that can transform existing database schema into a new version. It also provides database synchronisation mechanisms that can create database structure by specifying the model structure.
Advantage of sequelize:
Sequelize has all the characteristics that JavaScript has. It is easy to learn for web developer who knows JavaScript.
Setup and Create Project:
Execute the following command in the terminal for creating the Project:
mkdir sequelize_node_mysql_express
Navigate to the Project folder:
cd sequelize_node_mysql_express
Execute below command: This command will create package.json file.
Install the packages by executing below commands:
Create ‘models’ folder and files: Create models — author and book.
Create a database as ‘demo’ in mysql database:
Now in Model:
./model/author.js
./model/book.js
inside constants.js file
File sequelize.js using for ORM and define relationships:
inside sequelize.js file
Creating a api in index.js file using express:
Server run:
Go to Project and execute the below command in the terminal:
After executing the above command, in the ‘demo’ database two tables ‘authors’ and ‘books’ will be created.