I have shared some simple steps to create a Node.js MySQL CRUD operation with an example. The CRUD app performs mainly four operations like create, read, update & delete. All these operations are the most important to build any web applications.
For your better understanding, you should see the following points –
- C: CREATE – To insert new data into the database
- R: READ – To display data on the web page
- U: UPDATE – To update existing data in the database
- D: DELETE – To delete existing data from the database
If you want to see the node js crud example with MySQL then you must read all the given points in this tutorial. So that you will be able to implement it in your project.
Create CRUD Operations Using Node.js, Express & MySQL
Before, creating Node.js MySQL CRUD App, you must configure all the following steps –
Install Express Application
First of all, Install Basic Express Application and create the following necessary folders & files. Here, default folders & files of the express application are not shown.
nodeapp/ |__controllers/ | |__create-controller.js | |__read-controller.js | |__update-controller.js | |__delete-controller.js |__models/ | |__create-model.js | |__read-model.js | |__update-model.js | |__delete-model.js |__routes/ | |__create-route.js | |__read-route.js | |__update-route.js | |__delete-route.js |__views/ | |__crud-form.ejs | |__create-table.ejs |__app.js |__database.js
Create MySQL Database & Table
Create a Database with the name nodeapp
using the following query
Create a table with the name crud
into the MySQL database nodeapp
as the following query
Table Name – users
CREATE TABLE `users` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `full_name` varchar(255) DEFAULT NULL, `email_address` varchar(255) DEFAULT NULL, `city` varchar(255) DEFAULT NULL, `country` varchar(255) DEFAULT NULL )
Connect Node.js App to MySQL Database
- First, make sure the MySQL module must be installed
- Create
database.js
file in the root folder - Write the following script to connect Node.js express to MySQL Database.
Here is the script of Node.js MySQL database connection
File Name – database.js
var mysql = require('mysql'); var conn = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'nodeapp' }); conn.connect(function(err) { if (err) throw err; console.log('Database is connected successfully !'); }); module.exports = conn;
Create Data Using Node.js and MySQL
Now, We are going to configure the first part of the CRUD operation. In this part, we have to create data into the database using Node.js & MYSQL. So, we must implement all the following steps –
The Model to create data
- Include database connection file
database.js
- Create a method
createData
with two parameters likeinputData
&callback
and write SQL query to insert data into thecrud
table.inputData
– It will take input values from thecreateData
method of controllers/create.jscallback
– It will return the created value within itself.
File Name – create-model.js
var db=require('../database'); module.exports={ createData:function(inputData,callback){ var sql = 'INSERT INTO crud SET ?'; db.query(sql, inputData,function (err, data) { if (err) throw err; return callback(data); }); } }
The Controller to create data
- Include the model file
create.js
usingrequire('../models/create')
and assign to a variablecreateModel
. - Create
crudForm
method to display crud form in the browser - Also, Create a method
createData
with two parameters likereq
res
and configure the following steps –- Create an object
inputData
with all input values coming from the form - Pass
inputData
to thecreateData
method of the modelcreateModel
- After creating data successfully, redirect to the form.
- Create an object
File Name – create-controller.js
var createModel=require('../models/create-model'); module.exports={ crudForm:function(req, res) { res.render('crud-form'); }, createData:function(req,res){ const inputData= { full_name: req.body.full_name, eamil_address: req.body.email_address, city : req.body.city, country : req.body.country }; createModel.createData(inputData,function(data){ res.redirect('/crud/form'); console.log(data.affectedRows + " record created"); }); } }
The View to create data
Create a CRUD form with the following input attributes –
Field Name | Type Attribute | name attribute |
full Name | type=”text” | name=”full_name” |
Email Address | type=”email” | name=”email_address” |
City | type=”text” | name=”city” |
Country | type=”text” | name=”country” |
Also, you must declare the following attributes –
- method =”post”
- action =”/crud/create”
Now, use the following complete HTML code to create a CRUD form.
File Name – crud-form.ejs
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> .crud-form { height: 100vh; border: 2px solid #f1f1f1; padding: 16px; background-color: white; width: 30%;} input{ width: 100%; padding: 15px; margin: 5px 0 22px 0; display: inline-block; border: none; background: #f1f1f1;} input[type=text]:focus, input[type=password]:focus { background-color: #ddd; outline: none;} button[type=submit] { background-color: #434140; color: #ffffff; padding: 10px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; opacity: 0.9; font-size: 20px;} button[type=submit]:hover { background-color:#3d3c3c;} </style> </head> <body> <!--====form section start====--> <!--====form section start====--> <div class="crud-form"> <form action="<%=(typeof editData!='undefined')?'/crud/update/'+editData.id:'/crud/create'%>" method="POST"> <input type="text" placeholder="Full Name" name="full_name" required value="<%=(typeof editData!='undefined')? editData.full_name:''%>"> <input type="email" placeholder="Email Address" name="email_address" required value="<%=(typeof editData!='undefined')? editData.email_address:''%>"> <input type="city" placeholder=" City" name="city" required value="<%=(typeof editData!='undefined')? editData.city:''%>"> <input type="text" placeholder="Country" name="country" required value="<%=(typeof editData!='undefined')? editData.country:''%>"> <button type="submit">Submit</button> </div> </div> <!--====form section start====--> <!--====form section start====--> </body> </html>
The Route to create data
- Include express module & access a router from it.
- Also, include a controller file create.js using
require('../controllers/create')
assign it tocreateController
- Create a route
/form
to display the CRUD form. - Also, create another route
/create
to insert data into the database. It will call when you submit the CRUD form - At last, export the router
File Name – create-route.js
var express = require('express'); var createController=require('../controllers/create-controller'); var router = express.Router(); // to display form router.get('/form', createController.crudForm ); // to create data router.post('/create', createController.createData); module.exports = router;
Read Data Using Node.js and MySQL
Now, We are going to configure the second part of the CRUD operation. In this part, we have to read/display data from the database using Node.js & MYSQL. So, we must implement all the following steps –
The Model to read data
- Include database connection file
database.js
- Create a method
readData
with a parameter likecallback
and write SQL queries to fetch data from thecrud
table.callback
– It will return the fetched value within itself.
File Name – read-model.js
var db=require('../database'); module.exports={ readData:function(callback){ var sql='SELECT * FROM crud'; db.query(sql, function (err, data, fields) { if (err) throw err; return callback(data); }); } }
The Controller to read data
- Include the model file
read.js
usingrequire('../models/read')
and assign to a variablereadModel
. - Create a method
readData
with two parameters likereq
res
and configure the following steps –- Create an object
inputData
with all input values coming from the form - Fetch data using
readData
method of the modelcreateModel
- Render and send fetched data to the crud table
- Create an object
File Name – read-controller.js
var readModel=require('../models/read-model'); module.exports={ readData:function(req,res){ readModel.readData(function(data){ res.render('crud-table', {fetchData:data}); }); } }
The View to read data
Now create a CRUD table in the views folder and write HTML code to create a table. After that, display all the records form the crud
database using fetchData
that comes from /read
route.
File Name – crud-table.ejs
<!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> table, td, th { border: 1px solid #ddd; text-align: left; } table{ border-collapse: collapse; width: 50%; } .table-data{ overflow-x:auto; } th, td { padding: 15px; } </style> </head> <body> <div class="table-data"> <table border="1" > <tr> <th>S.N</th> <th>Full Name</th> <th>Email Address</th> <th>City</th> <th>Country</th> <th>Edit</th> <th>Delete</th> </tr> <% if(fetchData.length!=0){ var i=1; fetchData.forEach(function(data){ %> <tr> <td><%=i; %></td> <td><%=data.full_name %></td> <td><%=data.email_address %></td> <td><%=data.city %></td> <td><%=data.country %></td> <td><a href="/crud/edit/<%=data.id%>">Edit</a></td> <td><a href="/crud/delete/<%=data.id%>">Delete</a></td> </tr> <% i++; }) %> <% } else{ %> <tr> <td colspan="7">No Data Found</td> </tr> <% } %> </table> </div> </body> </html>
The Route to read data
- Include express module & access a router from it.
- Also, include a controller file create.js using
require('../controllers/read')
assign it toreadController
- Create a route
/read
to display the CRUD table - At last, export the router
File Name – read-route.js
var express = require('express'); var readController=require('../controllers/read-controller'); var router = express.Router(); // to display data router.get('/read', readController.readData); module.exports = router;
Update Data Using Node.js and MySQL
Now, We are going to configure the third part of the CRUD operation. In this part, we have to update data from the database using Node.js & MYSQL. So, we must implement all the following steps –
The Model to update data
Configure the following points to edit data
- Include database connection file
database.js
- Create a method
editData
with two parameters likeeditId
&callback
and write SQL query to fetch data based oneditId
from thecrud
table.editId
– It will take input values from theeditData
method of controllers/update.jscallback
– It will return the fetched value within itself.
Also, configure the following points to update data
- Create a method
updateData
with three parameters likeinputData
updateId
&callback
and write SQL query to update data based onupdateId
from thecrud
table.inputData
– It will take input values from thecreateData
method of controllers/create.jsupdateId
– Also, It will take input values from theupdateData
method of controllers/update.jscallback
– It will return the updated value within itself.
File Name – update-model.js
var db=require('../database'); module.exports={ editData:function(editId, callback){ var sql=`SELECT * FROM crud WHERE id=${editId}`; db.query(sql, function (err, data) { if (err) throw err; return callback(data[0]); }); }, updateData:function(inputData,updateId,callback){ var sql = `UPDATE crud SET ? WHERE id= ?`; db.query(sql, [inputData, updateId], function (err, data) { if (err) throw err; return callback(data); }); } }
The Controller to update data
Configure the following steps to display the existing record based on editId
in the form
- Include the model file
update.js
usingrequire('../models/update')
and assign to a variableupdateModel
. - Create a method
editData
with two parameters likereq
res
and configure the following steps –- Get an id using
req.params.id
and assign it to theeditId
- Pass
editId
to theupdateData
of modelupdateModel
. - Render and send fetched data through
editData
to the crud form.
- Get an id using
Also, configure the following steps to update the existing record based on updateId
- Create a method
updateData
with two parameters likereq
res
and configure the following steps –- Create an object
inputData
with all input values coming from the form - Get an id using
req.params.id
and assign it to theupdateId
- Pass
inputData
&updateId
to theupdateData
of modelupdateModel
. - After that, redirect to the crud table page
- Create an object
File Name – update-controller.js
var updateModel=require('../models/update-model'); module.exports={ editData:function(req,res){ const editId=req.params.id; updateModel.editData(editId,function(data){ res.render('crud-form', { editData:data}); console.log(data.affectedRows + " record fetched"); }); }, updateData:function(req,res){ const inputData= { full_name: req.body.full_name, eamil_address: req.body.email_address, city : req.body.city, country : req.body.country }; const updateId=req.params.id; updateModel.updateData(inputData,updateId,function(data){ res.redirect('/crud/read'); console.log(data.affectedRows + " record(s) updated"); }); } }
The View to update data
You can use the CRUD form to update data. So, when you click the edit button then it will display existing input values based on the specified id.
Finally, you just replace the existing code of the CRUD form with the following HTML code. Don’t worry this code will work for both creating & updating data.
File Name – crud-form.ejs
The Route to update data
- Include express module & access a router from it.
- Also, include a controller file create.js using
require('../controllers/update')
assign it toupdateController
- Create a route
/edit/:id
to fetch data based onid
that must be a number. It will call when you click the edit button in the CRUD table - Also, create another route
/update/:id
to update data based onid
that must be a number. It will call when you submit the CRUD form - At last, export the router
File Name – update-route.js
var express = require('express'); var updateController=require('../controllers/update-controller'); var router = express.Router(); // to edit data router.get('/edit/:id', updateController.editData); // to update data router.post('/update/:id', updateController.updateData); module.exports = router;
Delete Data Using Node.js and MySQL
Now, We are going to configure the fourth part of the CRUD operation. In this part, we have to delete data from the database using Node.js & MYSQL. So, we must implement all the following steps –
The Model to delete data
- Create a method
deleteData
with two parameters likedeleteId
&callback
and write SQL queries to delete data based ondeleteId
from thecrud
table.deleteId
– It will take input values from thedeleteData
method of controllers/update.jscallback
– It will return the deleted value within itself.
File Name – delete-model.js
var db=require('../database'); module.exports={ deleteData:function(deleteId,callback){ var sql = 'DELETE FROM crud WHERE id = ?'; db.query(sql, [deleteId], function (err, data) { if (err) throw err; return callback(data); }); } }
The Controller to delete data
- Include the model file
delete.js
usingrequire('../models/delete')
and assign to a variabledeleteModel
. - Create a method
deleteData
with two parameters likereq
res
and configure the following steps –- Get an id using
req.params.id
and assign it to thedeleteId
- Pass
deleteId
to thedeleteData
of modeldeleteModel
. - At last, redirect to the crud table.
- Get an id using
File Name – delete-controller.js
var deleteModel=require('../models/delete-model'); module.exports={ deleteData:function(req,res){ const deleteId=req.params.id; deleteModel.deleteData(deleteId,function(data){ res.redirect('/crud/read'); console.log(data.affectedRows + " record deleted"); }); } }
The Route to delete data
- Include express module & access a router from it.
- Also, include a controller file create.js using
require('../controllers/delete')
assign it todeleteController
- Create a route
/delete/:id
to delete data based onid
that must be a number. It will call when you click the delete button in the CRUD table - At last, export the router
File Name – delete-route.js
var express = require('express'); var deleteController=require('../controllers/delete-controller'); var router = express.Router(); // to delete data router.get('/delete/:id', deleteController.deleteData); module.exports = router;
Load all Routes in App.js
Now, you must load all the created routes in the root file app.js. You will get various default code ( not showing here ) in the app.js file while you install the express application.
File Name – app.js
var createRouter = require('./routes/create-route'); var readRouter = require('./routes/read-route'); var updateRouter = require('./routes/update-route'); var deleteRouter = require('./routes/delete-route'); app.use('/crud', createRouter); app.use('/crud', readRouter); app.use('/crud', updateRouter); app.use('/crud', deleteRouter);
Run Node.js CRUD Operation
You can use the following two main routes to run Node.js CRUD operation –
http://localhost:3000/crud/form // call it on GET request to display crud form http://localhost:3000/crud/read // call it on GET request to display data
My Suggestion
Dear developers, I hope you have understood the above script, Now you are able to develop a CRUD Operation using Node.js & MySQL. So, Continue to visit my site, I will share more tutorials related to Node.js / Express as soon as possible.
If you have any doubts or questions. You can directly ask me through the below comment box.
The files mentioned above have been created in different folders specified.
How do we run this application
Hi Gopal, You can run this application through following steps
npm start
http://localhost:3000/crud/form
in your browserGetting the below:
Not Found
404
NotFoundError: Not Found
After entering the above code snippets into respective files in the folders, how do you run this?
After starting npm and executing app.js, should we typing a URL to get the page? what URL and at which port would it listen?
You can enter the following url in your browser
http://localhost:3000/crud/form
– for the HTML form to insert datahttp://localhost:3000/crud/create
– It will redirect when you sumbit formhttp://localhost:3000/crud/fetch
– for displaying data on the pageThe above URLs give me 404. Anything that should be verified prior to running it?
read the carefully complete article. After that, execute gain. It will definitely work