Curd Operation Node MonogoDb Express EJS
In this tutorial we will leran how to insert ,update, read and delete data using Node Express Mongodb EJS .
Step 1 : First create a folder in any drive in your computer , in my case i created
"curd_with_mongo" folder
Step 2 : Open this folder in vs Code editor
Step 3 : Now Open a terminal and hit bellow commant
npm init
after npm init you will get package.json in your project .
Step 4 : Now you have to install some node package like express ,mongoose ,ejs and nodemon also.
npm install express mongoose ejs nodemon
after installing you will get these package version information inside dependencies in package.json file.
Step 5 : Now Create a file as named "index.js" and put bellow code in this file .
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log("Example app listening at http://localhost:"+port);
});
This above code will create a server where you can serve your output
Step 6 : Now Run Your Project With Bellow Command
node index.js
if you will getting bellow output in terminal it means every thing is ok or server setup is correctly.
Example app listening at http://localhost:3000
you can see the output in your web browser just open above url in your browser ,you will see :
Hello World!
Now CURD OPERATION will start form here ,first we will insert data in mongodb then we will test them then create anothere operation
Step 7 : Create a "views" folder in your project .
Step 8 : Now Create a ejs file inside "views" folder for design a form which will insert data in mongodb as named "insertdata.ejs" put bellow code in insertdata.ejs file .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<center>
<fieldset style="width: 400px;">
<legend>
<h2 style="color: maroon;">Register Employee Data</h2>
</legend>
<form action="/register" method="post">
<table>
<tr>
<td>Name :</td>
<td>
<input type="text" placeholder="Name" name="name">
</td>
</tr>
<tr>
<td>Email :</td>
<td>
<input type="text" placeholder="Email" name="email">
</td>
</tr>
<tr>
<td>address :</td>
<td>
<input type="text" placeholder="Address" name="address">
</td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</fieldset>
</center>
</body>
</html>
Step 9 : Now Design index.js file with some code
add required bellow module in index file
const ejs = require("ejs");
Specified ejs engine in index.js file
app.set("view engine", "ejs");
Now render the insertdata.ejs in perticuler path in browser so add bellow code
to index.js
app.get("/insert_employee", function (req, res) {
res.render("insertdata");
});
Now complete index.js file looks like this :
const express = require('express');
const ejs = require("ejs");
const app = express();
const port = 3000;
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
// for render the inserdata.ejs file in browser
app.get("/insert_employee", function (req, res) {
res.render("insertdata");
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log("Example app listening at http://localhost:"+port);
});
Now open the bellow url in your browser
http://localhost:3000/insert_employee
you will get outpur like picture
Step 10 : Now Make Connection and schema for mongodb database .
add this module in index.js
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
add body parser in index.js
app.use(bodyParser.urlencoded({
extended: true
}));
connection and schema
mongoose.connect("mongodb://127.0.0.1:27017/EmployeeDB", {
useNewUrlParser: true,
useUnifiedTopology: true
});
const employeeSchema = {
name: String,
email: String,
address: String,
};
const Employee = mongoose.model("Employee", employeeSchema);
Step 11 : insert Record in database (Add bellow code in index.js file )
app.post("/register", function (req, res) {
// console.log(req.body.uname);
// console.log(req.body.email);
// console.log(req.body.address)
const employee = new Employee({
name: req.body.uname,
email: req.body.email,
address: req.body.address,
});
employee.save()
.then(() => {
return res.redirect("/")
})
.catch(function (err) {
console.log(err);
});
});
Now index.js will be looks like this
complete insertion functionality
const express = require('express');
const ejs = require("ejs");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({
extended: true
}));
mongoose.connect("mongodb://127.0.0.1:27017/EmployeeDB", {
useNewUrlParser: true,
useUnifiedTopology: true
});
const employeeSchema = {
name: String,
email: String,
address: String,
};
const Employee = mongoose.model("Employee", employeeSchema);
// for render the inserdata.ejs file in browser
app.get("/insert_employee", function (req, res) {
res.render("insertdata");
});
// insert Record in database
app.post("/register", function (req, res) {
// console.log(req.body.uname);
// console.log(req.body.email);
// console.log(req.body.address)
const employee = new Employee({
name: req.body.uname,
email: req.body.email,
address: req.body.address,
});
employee.save()
.then(() => {
return res.redirect("/")
})
.catch(function (err) {
console.log(err);
});
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log("Example app listening at http://localhost:" + port);
});
Now Run your project again and fill the registeration form and submit form data, you will get data in mongodb
Now fetch data from database and show in browser
Step 12 : Create a new ejs file inside "views" folder as named "showdata.ejs" for showing the data
add bellow code in showdata.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<center>
<fieldset style="width: 400px;">
<legend>
<h1 style="color: maroon;">Employee List</h1>
</legend>
<a style="font-size: 18px;color: red;" href="/insert_employee">Register Data</a>
<br>
<br>
<table border="1">
<thead>
<tr>
<th>
Name:
</th>
<th>
Email:
</th>
<th>
Address:
</th>
</tr>
</thead>
</table>
</fieldset>
</center>
</body>
</html>
Step : 13 Now render this ejs file in index,js so add bellow code in index,js
app.get("/", (req, res) => {
res.render("showdata");
});
If you will Run your project ,you will get output in your browser like bellow
Step 14 : Add bellow code in index.js file for fetching data
app.get("/", (req, res) => {
Employee.find().then((result) => {
console.log(result);
return res.render("showdata", {
data: result
});
}).catch(function (err) {
console.log(err)
}
)
});
after above code in index.js file looks like bellow
const express = require('express');
const ejs = require("ejs");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({
extended: true
}));
mongoose.connect("mongodb://127.0.0.1:27017/EmployeeDB", {
useNewUrlParser: true,
useUnifiedTopology: true
});
const employeeSchema = {
name: String,
email: String,
address: String,
};
const Employee = mongoose.model("Employee", employeeSchema);
// for render the inserdata.ejs file in browser
app.get("/insert_employee", function (req, res) {
res.render("insertdata");
});
// insert Record in database
app.post("/register", function (req, res) {
// console.log(req.body.uname);
// console.log(req.body.email);
// console.log(req.body.address)
const employee = new Employee({
name: req.body.uname,
email: req.body.email,
address: req.body.address,
});
employee.save()
.then(() => {
return res.redirect("/")
})
.catch(function (err) {
console.log(err);
});
});
//fetching data form database and show in showdata file
app.get("/", (req, res) => {
Employee.find().then((result) => {
console.log(result);
return res.render("showdata", {
data: result
});
}).catch(function (err) {
console.log(err)
}
)
});
// app.get('/', (req, res) => {
// res.send('Hello World!');
// });
app.listen(port, () => {
console.log("Example app listening at http://localhost:" + port);
});
Step 15 : Now update "showdata.ejs" file with some code to display data and bellow code is complete final code for showdaa.ejs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<center>
<fieldset style="width: 450px;">
<legend>
<h1 style="color: maroon;">Employee List</h1>
</legend>
<a style="font-size: 18px;color: red;" href="/insert_employee">Register Data</a>
<br>
<br>
<table border="1">
<thead>
<tr>
<th>
Name:
</th>
<th>
Email:
</th>
<th>
Address:
</th>
</tr>
</thead>
<tbody>
<% if(data.length){ for(var i=0; i< data.length; i++) {%>
<tr>
<td>
<%= data[i].name %>
</td>
<td>
<%= data[i].email%>
</td>
<td>
<%= data[i].address%>
</td>
<td> <a href="edit/<%= data[i]._id%>">Edit</a>
<a href="delete/<%= data[i]._id%>">delete</a>
</td>
</tr>
<% } }else{ %>
<tr>
<td colspan="3">No user</td>
</tr>
<% } %>
</tbody>
</table>
</fieldset>
</center>
</body>
</html>
output will be bellow
Step 16 : add bellow code in index.ejs for delete Data form database
// DELETE USER
app.get("/delete/(:id)", function (req, res) {
Employee.findByIdAndRemove(req.params.id).then(() => {
return res.redirect("/")
}).catch((err) => {
console.log("err", err)
});
})
Step 17 : create a ejs file inside "views" folder as named "editdata.ejs" for design a update data form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<center>
<h1>
<%= title%>
</h1>
<form action="/updateuser/<%=data.id%>" method="post">
<table>
<tr>
<td>
<input type="text" value="<%= data.name %>" placeholder="Email" name="uname">
</td>
</tr>
<tr>
<td>
<input type="text" value="<%= data.email %>" placeholder="Email" name="email">
</td>
</tr>
<tr>
<td>
<input type="text" value="<%= data.address %>" placeholder="Query" name="query">
</td>
</tr>
<tr>
<td>
<button type="submit">Update Now</button>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Step 17 : Now Render the editdata page so add bellow code in "index.js"
app.get("/edit/(:id)", function (req, res) {
Employee.findById(req.params.id).then((data) => {
res.render("editdata", {
title: "Update User Details",
data: data
});
}).catch((err) => {
console.log(err)
})
});
Step 18 : Now update the Data, add bellow code in index.js
app.post("/updateuser/(:id)", function (req, res) {
Employee.findByIdAndUpdate(req.params.id, { $set: { name: req.body.uname,email: req.body.email,
address: req.body.address } }, { new: true }).then((data) => {
console.log("update");
return res.redirect("/")
}).catch((err) => {
console.log(err);
})
})
Final index.js file look like bellow
const express = require('express');
const ejs = require("ejs");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({
extended: true
}));
mongoose.connect("mongodb://127.0.0.1:27017/EmployeeDB", {
useNewUrlParser: true,
useUnifiedTopology: true
});
const employeeSchema = {
name: String,
email: String,
address: String,
};
const Employee = mongoose.model("Employee", employeeSchema);
// for render the inserdata.ejs file in browser
app.get("/insert_employee", function (req, res) {
res.render("insertdata");
});
// insert Record in database
app.post("/register", function (req, res) {
// console.log(req.body.uname);
// console.log(req.body.email);
// console.log(req.body.address)
const employee = new Employee({
name: req.body.uname,
email: req.body.email,
address: req.body.address,
});
employee.save()
.then(() => {
return res.redirect("/")
})
.catch(function (err) {
console.log(err);
});
});
//fetching data form database and show in showdata file
app.get("/", (req, res) => {
Employee.find().then((result) => {
console.log(result);
return res.render("showdata", {
data: result
});
}).catch(function (err) {
console.log(err)
}
)
});
// DELETE USER
app.get("/delete/(:id)", function (req, res) {
Employee.findByIdAndRemove(req.params.id).then(() => {
return res.redirect("/")
}).catch((err) => {
console.log("err", err)
});
})
//DATA GET IN EDIT FORM
app.get("/edit/(:id)", function (req, res) {
Employee.findById(req.params.id).then((data) => {
res.render("editdata", {
title: "Update User Details",
data: data
});
}).catch((err) => {
console.log(err)
})
});
// UPDATE DATA
app.post("/updateuser/(:id)", function (req, res) {
Employee.findByIdAndUpdate(req.params.id, { $set: { name: req.body.uname,email: req.body.email,
address: req.body.address } }, { new: true }).then((data) => {
console.log("update");
return res.redirect("/")
}).catch((err) => {
console.log(err);
})
})
// app.get('/', (req, res) => {
// res.send('Hello World!');
// });
app.listen(port, () => {
console.log("Example app listening at http://localhost:" + port);
});
Last Updated on : 19th Oct 2023 17:26:19 PM
Latest Update
- JavaScript Interview Question MongoDb Command Curd Operation Node MonogoDb Express EJSC Practice Question Example Data Structure with CPPjava practice questionCurd operation with localstorage in javascriptComplete curd operation in react with json server and axios and router-domCPP Practice Question React Interview Question Java Pattern Program