Introduction:
In this tutorial, we'll walk through the process of building a CRUD (Create, Read, Update, Delete) application using Node.js and MongoDB. CRUD applications are fundamental in web development as they facilitate the basic operations for managing data in a database. We'll leverage the power of Node.js for the backend logic and MongoDB as the database to store our data. By the end of this tutorial, you'll have a solid understanding of how to create a fully functional CRUD application.
Prerequisites:
Before we begin, make sure you have the following installed on your system:
- Node.js
- MongoDB
Step 1: Setting Up Your Project:
Start by creating a new directory for your project and navigate into it using your terminal or command prompt.
mkdir node-crud-app
cd node-crud-app
Initialize a new Node.js project using npm.
npm init -y
Step 2: Installing Dependencies:
Next, we need to install the necessary dependencies for our project. We'll use Express.js as our web framework and Mongoose as the MongoDB ODM (Object Data Modeling) library.
npm install express mongoose body-parser
Step 3: Setting Up MongoDB:
In this tutorial, we have use Cloud Mongo DB Database. So in below video tutorial, you can find step by step guide for how to create Mongo DB Schema or Database in the Cloud.
Step 4: Creating the Server:
Create a file named server.js in your project directory and set up a basic Express server.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
app.use(express.static(__dirname));
Step 5: Connecting to MongoDB:
Add the code to connect your Node.js application to MongoDB using Mongoose.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
app.use(express.static(__dirname));
mongoose.connect('mongodb+srv://johnsmith174:xxxxx@cluster0.8dbkdwt.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0');
const connect = mongoose.connection;
connect.on('error', console.error.bind(console, 'MongoDB connection error:'));
connect.once('open', () => {
console.log('Connected to MongoDB');
});
Step 6: Creating Models:
Define a schema for your MongoDB documents and create models using Mongoose.
server.js
const userSchema = new mongoose.Schema({
name : String,
email : String,
age : Number
});
const User = mongoose.model('User', userSchema);
Step 7: Implementing CRUD Operations:
Now, let's implement the CRUD operations for our application - Create, Read, Update, and Delete.
Create Operation (POST):
The create operation involves adding new items to our database. We'll define a route to handle incoming POST requests to create new items.
So first we have to create one get route in server.js file for load HTML file in the browser.
server.js
app.get('/', async (request, response) => {
response.sendFile(__dirname + '/user.html');
});
Next we have to create one user.html file and under this file, we have to create one button and when we have click on button then bootstrap modal must be pop up on web page and under modal we will make user form for insert data into MongoDB.
user.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Build a CRUD App with Node.js and MongoDB</title>
</head>
<body>
<div class="container">
<h1 class="text-center mb-5 mt-5 text-danger"><b>Build a CRUD App with Node.js and MongoDB - Insert Data into MongoDB Database - 2</b></h1>
<div class="card mb-5">
<div class="card-header">
<div class="row">
<div class="col col-6">Sample Data</div>
<div class="col col-6">
<button type="button" class="btn btn-primary btn-sm float-end" onclick="makeModal('Add User', 'Add', 'insertData')">Add</button>
</div>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
</div>
</div>
</div>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div id="modalArea"></div>
<script>
var userModalElement;
function makeModal(title, button_value, callback)
{
let html = `
<div class="modal" tabindex="-1" id="userModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="userform">
<div class="modal-header">
<h5 class="modal-title">${title}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label>Name</label>
<input type="text" name="name" id="name" class="form-control" />
</div>
<div class="mb-3">
<label>Email</label>
<input type="email" name="email" id="email" class="form-control" />
</div>
<div class="mb-3">
<label>Age</label>
<input type="number" name="age" id="age" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="${callback}()">${button_value}</button>
</div>
</form>
</div>
</div>
</div>
`;
document.querySelector('#modalArea').innerHTML = html;
userModalElement = new bootstrap.Modal(document.getElementById('userModal'));
userModalElement.show();
}
function insertData()
{
let formElement = document.getElementById('userform');
const formData = new FormData(formElement);
// Convert formData to JSON
const jsonData = {};
formData.forEach((value, key) => {
jsonData[key] = value;
});
// Make a POST request using Fetch API
fetch('/users', {
method : 'POST',
body : JSON.stringify(jsonData),
headers : {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
})
.then(data => {
userModalElement.hide();
getData();
});
}
</script>
Next we have goes to server.js file and here we have to create one POST route for handle form data for insert data into MongoDB.
server.js
app.post('/users', async (request, response) => {
const user = new User({
name : request.body.name,
email : request.body.email,
age : request.body.age
});
const newItem = await user.save();
response.status(201).json({scuccess:true});
});
Read Operation (GET):
So for read data operation, first we have goest to user.html file and here we have to create one HTML table and then after we have goes to JavaScript code part, and here we have to create one getData() function which will send fetch data request to node application route and display on web page, and call this function into insertData() function, so when new data has been inserted then it will display last inserted data on web also.
user.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Build a CRUD App with Node.js and MongoDB</title>
</head>
<body>
<div class="container">
<h1 class="text-center mb-5 mt-5 text-danger"><b>Build a CRUD App with Node.js and MongoDB - Insert Data into MongoDB Database - 2</b></h1>
<div class="card mb-5">
<div class="card-header">
<div class="row">
<div class="col col-6">Sample Data</div>
<div class="col col-6">
<button type="button" class="btn btn-primary btn-sm float-end" onclick="makeModal('Add User', 'Add', 'insertData')">Add</button>
</div>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody id="dataArea"></tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div id="modalArea"></div>
<script>
var userModalElement;
function makeModal(title, button_value, callback)
{
let html = `
<div class="modal" tabindex="-1" id="userModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="userform">
<div class="modal-header">
<h5 class="modal-title">${title}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label>Name</label>
<input type="text" name="name" id="name" class="form-control" />
</div>
<div class="mb-3">
<label>Email</label>
<input type="email" name="email" id="email" class="form-control" />
</div>
<div class="mb-3">
<label>Age</label>
<input type="number" name="age" id="age" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="${callback}()">${button_value}</button>
</div>
</form>
</div>
</div>
</div>
`;
document.querySelector('#modalArea').innerHTML = html;
userModalElement = new bootstrap.Modal(document.getElementById('userModal'));
userModalElement.show();
}
function insertData()
{
let formElement = document.getElementById('userform');
const formData = new FormData(formElement);
// Convert formData to JSON
const jsonData = {};
formData.forEach((value, key) => {
jsonData[key] = value;
});
// Make a POST request using Fetch API
fetch('/users', {
method : 'POST',
body : JSON.stringify(jsonData),
headers : {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
})
.then(data => {
userModalElement.hide();
getData();
});
}
getData();
function getData(){
fetch('/users')
.then(response => {
return response.json();
})
.then(data => {
let html = '';
if(data.length > 0){
data.map((row) => {
html += `
<tr>
<td>${row.name}</td>
<td>${row.email}</td>
<td>${row.age}</td>
<td></td>
</tr>
`;
});
} else {
html = '<tr><td colspan="4" class="text-center">No Data Found</td></tr>';
}
document.getElementById('dataArea').innerHTML = html;
});
}
</script>
Next The read operation involves fetching existing items from the database. We'll define a route to handle incoming GET requests to retrieve items in server.js file.
server.js
app.get('/users', async (request, response) => {
const users = await User.find();
response.status(200).json(users);
});
Update Operation (PUT/PATCH):
For Update MongoDB data, first we have goes to user.html file and under this file, we have to create edit button in each of data, which will send get request for fetch single user data from MongoDB data and then after we have to create one editData() function which will be called when we have submit form data. So it will send PUT request to node crud application.
user.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Build a CRUD App with Node.js and MongoDB</title>
</head>
<body>
<div class="container">
<h1 class="text-center mb-5 mt-5 text-danger"><b>Build a CRUD App with Node.js and MongoDB - Delete Data from MongoDB Database - 5</b></h1>
<div class="card mb-5">
<div class="card-header">
<div class="row">
<div class="col col-6">Sample Data</div>
<div class="col col-6">
<button type="button" class="btn btn-primary btn-sm float-end" onclick="makeModal('Add User', 'Add', 'insertData')">Add</button>
</div>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody id="dataArea"></tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div id="modalArea"></div>
<script>
var userModalElement;
function makeModal(title, button_value, callback)
{
let html = `
<div class="modal" tabindex="-1" id="userModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="userform">
<div class="modal-header">
<h5 class="modal-title">${title}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label>Name</label>
<input type="text" name="name" id="name" class="form-control" />
</div>
<div class="mb-3">
<label>Email</label>
<input type="email" name="email" id="email" class="form-control" />
</div>
<div class="mb-3">
<label>Age</label>
<input type="number" name="age" id="age" class="form-control" />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="${callback}()">${button_value}</button>
</div>
</form>
</div>
</div>
</div>
`;
document.querySelector('#modalArea').innerHTML = html;
userModalElement = new bootstrap.Modal(document.getElementById('userModal'));
userModalElement.show();
}
function insertData()
{
let formElement = document.getElementById('userform');
const formData = new FormData(formElement);
// Convert formData to JSON
const jsonData = {};
formData.forEach((value, key) => {
jsonData[key] = value;
});
// Make a POST request using Fetch API
fetch('/users', {
method : 'POST',
body : JSON.stringify(jsonData),
headers : {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
})
.then(data => {
userModalElement.hide();
getData();
});
}
getData();
function getData(){
fetch('/users')
.then(response => {
return response.json();
})
.then(data => {
let html = '';
if(data.length > 0){
data.map((row) => {
html += `
<tr>
<td>${row.name}</td>
<td>${row.email}</td>
<td>${row.age}</td>
<td>
<button type="button" class="btn btn-warning btn-sm" onclick="fetchSingleData('${row._id}')">Edit</button>
</td>
</tr>
`;
});
} else {
html = '<tr><td colspan="4" class="text-center">No Data Found</td></tr>';
}
document.getElementById('dataArea').innerHTML = html;
});
}
function fetchSingleData(id){
fetch(`/users/${id}`)
.then(response => {
return response.json();
})
.then(data => {
makeModal('Edit User', 'Edit', 'editData');
document.getElementById('name').value = data.name;
document.getElementById('email').value = data.email;
document.getElementById('age').value = data.age;
document.getElementById('user_id').value = data._id;
});
}
function editData(){
let formElement = document.getElementById('userform');
const formData = new FormData(formElement);
let jsonData = {};
formData.forEach((value, key) => {
jsonData[key] = value;
});
const userId = document.getElementById('user_id').value;
fetch(`/users/${userId}`, {
method : 'PUT',
body : JSON.stringify(jsonData),
headers : {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
})
.then(data => {
userModalElement.hide();
getData();
});
}
</script>
The update operation involves modifying existing items in the database. We'll define a route to handle incoming PUT or PATCH requests to update items.
server.js
app.get('/users/:id', async (request, response) => {
const user = await User.findById(request.params.id);
response.status(200).json(user);
});
app.put('/users/:id', async (request, response) => {
const userId = request.params.id;
// Fetch the user from the database
const user = await User.findById(userId);
user.name = request.body.name;
user.email = request.body.email;
user.age = request.body.age;
const updatedItem = await user.save();
response.status(200).json(updatedItem);
});
Delete Operation (DELETE):
For Delete MongoDB Data from Node CRUD Application, so first we have to create Delete button in each row of data in user.html file and then after we have to create deleteData() JavaScript function which will send DELETE data request to node route by using DELETE POST method.
user.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Build a CRUD App with Node.js and MongoDB</title>
</head>
<body>
<div class="container">
<h1 class="text-center mb-5 mt-5 text-danger"><b>Build a CRUD App with Node.js and MongoDB - Delete Data from MongoDB Database - 5</b></h1>
<div class="card mb-5">
<div class="card-header">
<div class="row">
<div class="col col-6">Sample Data</div>
<div class="col col-6">
<button type="button" class="btn btn-primary btn-sm float-end" onclick="makeModal('Add User', 'Add', 'insertData')">Add</button>
</div>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody id="dataArea"></tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div id="modalArea"></div>
<script>
var userModalElement;
function makeModal(title, button_value, callback)
{
let html = `
<div class="modal" tabindex="-1" id="userModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="userform">
<div class="modal-header">
<h5 class="modal-title">${title}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label>Name</label>
<input type="text" name="name" id="name" class="form-control" />
</div>
<div class="mb-3">
<label>Email</label>
<input type="email" name="email" id="email" class="form-control" />
</div>
<div class="mb-3">
<label>Age</label>
<input type="number" name="age" id="age" class="form-control" />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="${callback}()">${button_value}</button>
</div>
</form>
</div>
</div>
</div>
`;
document.querySelector('#modalArea').innerHTML = html;
userModalElement = new bootstrap.Modal(document.getElementById('userModal'));
userModalElement.show();
}
function insertData()
{
let formElement = document.getElementById('userform');
const formData = new FormData(formElement);
// Convert formData to JSON
const jsonData = {};
formData.forEach((value, key) => {
jsonData[key] = value;
});
// Make a POST request using Fetch API
fetch('/users', {
method : 'POST',
body : JSON.stringify(jsonData),
headers : {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
})
.then(data => {
userModalElement.hide();
getData();
});
}
getData();
function getData(){
fetch('/users')
.then(response => {
return response.json();
})
.then(data => {
let html = '';
if(data.length > 0){
data.map((row) => {
html += `
<tr>
<td>${row.name}</td>
<td>${row.email}</td>
<td>${row.age}</td>
<td>
<button type="button" class="btn btn-warning btn-sm" onclick="fetchSingleData('${row._id}')">Edit</button>
<button type="button" class="btn btn-danger btn-sm" onclick="deleteData('${row._id}')">Delete</button>
</td>
</tr>
`;
});
} else {
html = '<tr><td colspan="4" class="text-center">No Data Found</td></tr>';
}
document.getElementById('dataArea').innerHTML = html;
});
}
function fetchSingleData(id){
fetch(`/users/${id}`)
.then(response => {
return response.json();
})
.then(data => {
makeModal('Edit User', 'Edit', 'editData');
document.getElementById('name').value = data.name;
document.getElementById('email').value = data.email;
document.getElementById('age').value = data.age;
document.getElementById('user_id').value = data._id;
});
}
function editData(){
let formElement = document.getElementById('userform');
const formData = new FormData(formElement);
let jsonData = {};
formData.forEach((value, key) => {
jsonData[key] = value;
});
const userId = document.getElementById('user_id').value;
fetch(`/users/${userId}`, {
method : 'PUT',
body : JSON.stringify(jsonData),
headers : {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
})
.then(data => {
userModalElement.hide();
getData();
});
}
function deleteData(id){
if(confirm("Are you sure you want to delete this?")){
fetch(`/users/${id}`, {
method : 'DELETE',
headers : {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
})
.then(data => {
getData();
});
}
}
</script>
The delete operation involves removing items from the database. We'll define a route to handle incoming DELETE requests to delete items.
server.js
app.delete('/users/:id', async (request, response) => {
const userId = request.params.id;
// Fetch the user from the database
const user = await User.findById(userId);
await user.deleteOne();
response.status(200).json({ message : 'Deleted item' });
});
Step 8: Testing Your Application:
For test Mongo DB Node.js CRUD application in browser, so we have goes to terminal and run node server.jsthis command which will start Node Development server and provide us http://localhost:3000/ base url of our Node Application.
Conclusion:
Congratulations! You've successfully built a Node.js CRUD application with MongoDB. This tutorial covered the basics, but there's still room for improvement and expansion. Feel free to explore additional features and functionalities to enhance your application further.
can you please share the sql file and password of online examination system using php at siddheshj0815@gmail.com
ReplyDelete