How To Connect To MySql Database Using Sequlize In Express (Node) Application

In the previous tutorial, we already saw how to get started with node.js. We also created basic web APIs in Node JS using express framework.

Here, we are going to see how to connect to MySQL database using Sequlize. We will create a web API for a book library. So, a user will be able to fetch, add, update, and delete books. Again, we will be using postman for testing our APIs.

This entire tutorial is available on github

Software needed-

      1. Node JS - Environment

      2. MySQL – Your database provider

      3. Postman – Used for creating http requests like GET, PUT, POST, DELETE

      4. Sublime/Notepad++ - IDE for writing code.

Install MySQL from official website according to your platform (Win/ Mac/ Linux). It is recommended that you use some Integrated Development Environment so that it easy to read and interpret code.

Throughout these courses, we will be using sublime which is a cool IDE.

Before starting tutorial, I would like you to create a user and a database in your MySQL.

We will be continuing with the previous tutorial example. It is strongly encouraged that you watch previous tutorial before continuing.

  1.  MySQL Configuration – Create a config.json file in your project directory and paste the following snippet. You need to add the database name, username, and password so that express can talk to your database. 
    1. "dev": {  
    2. "driver""mysql",  
    3. "user""user of database",  
    4. "database""your database name",  
    5. "password""your database password"   
    6. }
  2.  Installing Dependencies - You need to install the following packages in your node.js project. Sequelize is  ORM through which you can connect and run sql queries on your MySql Database. It is actually a wrapper on mysql package. It is very easy to learn and has got excellent documentation on their website.

    Body-parser will help you to read body content of http requests. 

    1. npm install sequelize 
    2. npm install body-parser
    3. npm install mysql  
  3.  Setting up- Paste the following code snippet.

    You need to create a table in MySQL. In the database, you added in config.json. Name the table as books and add 3 rows - id (datatype int), bookName (datatype varchar(25) and bookPrice (datatype int)

                                                 

  1. var express = require('express');  
  2. var Sequelize = require('sequelize');  
  3. var config = require('./config.json');  
  4. var bodyParser = require('body-parser');  
  5.   
  6. var password = config.password ? config.password : null;  
  7.   
  8. var sequelize = new Sequelize(  
  9.     config.database,  
  10.     config.user,  
  11.     config.password, {  
  12.         logging: console.log,  
  13.         define: {  
  14.             timestamps: false  
  15.         }  
  16.     }  
  17. );  
  18.   
  19.   
  20. var app = express();  
  21. var port = 3000;  
  22. var router = express.Router(); // will help in adding routes  
  23. app.use(bodyParser.urlencoded());  
  24. app.use(bodyParser.json());  
Now, we will define a model for our book library. We will keep only 2 fields for books, i.e. bookName and bookPrice.
  1. var bookModel = sequelize.define('books', { //define your model  
  2. "bookName": Sequelize.INTEGER,  
  3. "bookPrice": Sequelize.INTEGER  
  4. });  
      4. Add GET Request-  
  1. app.use('/api', router); //this will add routing to your api.  
  2. //your api endpoint  localhost:3000/api/books  
  3.   
  4. router.get('/books'function(req, res) {  
  5.     bookModel.findAll().  
  6.     then(function(books) {  
  7.         res.status(200).json(books);  
  8.     }, function(error) {  
  9.        res.status(500).send(error);  
  10.     });  
  11. });  
  12.   
  13. app.listen(port, function() {  
  14.   
  15. });  
  16. console.log('my api is running on port:' + port);  
       5. Start up- Start you application through command line.      
  1. Node server.js  
       6. Testing up - Go to postman and enter this URL.
  1. http://localhost:3000/api/books  
      and select GET request and click SEND.

 
In response, if you see status 200, then it shows everything is working properly. You will not see any data because we don’t have any data stored in our table.
 
       7. Add other Requests- PUT, POST, DELETE
  1. router.get('/book/:id'function(req, res) {  
  2.     bookModel.findAll({  
  3.         where: {  
  4.             id: req.params.id  
  5.         }  
  6.     }).  
  7.     then(function(books) {  
  8.         res.status(200).json(books);  
  9.     }, function(error) {  
  10.         res.status(500).send(error);  
  11.     });  
  12. });  

  13. router.post('/book'function(req, res) {  
  14.     console.log(req.body);  
  15.     var data = {  
  16.         "bookName": req.body.bookName,  
  17.         "bookPrice": req.body.bookPrice  
  18.     };  
  19.   
  20.     bookModel.create(data).  
  21.     then(function(books) {  
  22.         res.status(200).json(books);  
  23.     }, function(error) {  
  24.         res.status(500).send(error);  
  25.     });  
  26. });  

  27. router.put('/book/:id'function(req, res) {  
  28.     var data = {  
  29.         id: req.params.id,  
  30.         bookName: req.body.bookName,  
  31.         bookPrice: req.body.bookPrice  
  32.     };  
  33.   
  34.     bookModel.update(data, {  
  35.         where: {  
  36.             id: data.id  
  37.         }  
  38.     }).  
  39.     then(function(book) {  
  40.         res.status(200).json(book);  
  41.     }, function(error) {  
  42.         res.status(500).send(error);  
  43.     });  
  44. });  
  45.   
  46. router.delete('/book/:id'function(req, res) {  
  47.     var data = {  
  48.         id: req.params.id  
  49.     };  
  50.   
  51.     bookModel.destroy({  
  52.         where: {  
  53.   
  54.             id: data.id  
  55.   
  56.         }  
  57.     }).  
  58.     then(function(book) {  
  59.         res.status(200).json(book);  
  60.     }, function(error) {  
  61.         res.status(500).send(error);  
  62.     });  
  63. });  
  64.   
  65.   
  66. app.listen(port, function() {  
  67.   
  68. });  
  69. console.log('my api is running on port:' + port);  
      8.  Final Testing
      We are done with creating all operation in our web API. We will be testing our API by adding book content.
 
 
      
         Here is a sample of GET request for fetching all books in our database. 
 
 
      Here is a sample of PUT request for updating a particular book.
 
 
 
      Here is a sample of Delete request for removing particular book.
 
 
Ebook Download
View all
Learn
View all