Sequelize with Node, Express & Mysql and it’s setup (ok)
https://medium.com/@irshad.vali/sequelize-with-node-express-mysql-and-its-setup-ae69f0c02df7
Last updated
https://medium.com/@irshad.vali/sequelize-with-node-express-mysql-and-its-setup-ae69f0c02df7
Last updated
Irshad ValiMar 16, 2019·4 min read
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:
Navigate to the Project folder:
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.
Create few get and post api as below:
POST
call api for creating author and book.
1- http://localhost:3001/demoApi/author
payload is:
{ “authorName”: “irshad vali }
2- http://localhost:3001/demoApi/book
payloads are:
{ “bookName”: “System Architecture”, “authorId”: 1 }
All
GET
Apis
1- Get all authors list
http://localhost:3001/demoApi/authors
2- Get all books list
http://localhost:3001/demoApi/books
3- Get Author by id
http://localhost:3001/demoApi/author/1
4- Get Book by id
http://localhost:3001/demoApi/book/1
5- Get Author and his books
http://localhost:3001/demoApi/authorHasManyBooks/1
That’s done, I hope this tutorial will be helpful for setup of sequelize and created api using sequelize, node, express and mysql.
You can get whole code of this tutorial from github link .