NodeJS API-Part 6 / Adding Sequelize and MySQL Database
This is the 6º tutorial of a complete series of building a production “NodeJS API using Express, MySQL and Sequelize”.
Full source code of this class is available at GitHub Martial Arts API Part 6
SETTING UP MYSQL
Before starting, we will configure our MySQL database. As this is not a MySQL tutorial, we will not go deep on this subject, if you have any problems I suggest you to take a course or just google your error.
We will have a database with a single table dojos
which holds two gyms.
If you want the MySQL code to create this database you can get it here.
INSTALLING MYSQL2 AND SEQUELIZE
Sequelize will be responsible to connect your API to MySQL data, and sequelize requires you to also install mysql2.
Run
npm install sequelize mysql2
CREATING YOUR MODEL
Remember that in Part 5 of our class we added router/controller but didn’t add model. Now it is the time.
We will use sequelize to create a representation of our table in our models/dojos.js
file.
This is pretty simples, the important part is inside Dojos.init()
where we define our mysql columns, we must put the exactly same name we put in the mysql database and specify the type, and in modelName where we must define our table name. All the rest are sequelize patterns.
You can find a full list of DataTypes in Sequelize DataTypes Documentation.
MODIFYING YOUR CONTROLLER
Now that your Dojo model is all set. You just need to import it and sequelize to your controller.
Instead of returning some dummy data, you first start a sequelize connection to your local database. By setting your parameters as in the code above.
In the end you just need to call the findAll()
method of your model and sequelize will take care of making the SELECT
query in your database.
NOTE: Don’t forget to make your method async
since we are performing asynchronous calls using await
.
Run your project using nodemon app.js
and use postman to call your server on localhost:8000/dojos
and you will see the following response.
ISN’T THAT AWESOME
Isn’t that awesome how we set up our server with real data from database with so few lines?
The most awesome part is that you will no longer need to perform MySQL queries as SELECT, INSERT, UPDATE, DELETE
. Yeahh! I am serious, sequelize will take care of it for you.
CONCLUSION
Checkout the following class where we will add complete CRUD to our project.
Full source code of this class is available at GitHub Martial Arts API Part 6