0% found this document useful (0 votes)
8 views7 pages

SP Ex-6

The document outlines the design and implementation of a simple MongoDB CRUD application using HTML, JavaScript, and Node.js with Express. It includes a front-end interface for adding, editing, and deleting records, as well as a back-end server for handling database operations. The application connects to a MongoDB database and provides functionality for sorting and displaying records in a table format.

Uploaded by

VENKATESH M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views7 pages

SP Ex-6

The document outlines the design and implementation of a simple MongoDB CRUD application using HTML, JavaScript, and Node.js with Express. It includes a front-end interface for adding, editing, and deleting records, as well as a back-end server for handling database operations. The application connects to a MongoDB database and provides functionality for sorting and displaying records in a table format.

Uploaded by

VENKATESH M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Design and Implement Simple application using MongoDB

Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MongoDB CRUD App</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid black;
padding: 10px;
text-align: left;
}
th {
background-color: #f2f2f2;
cursor: pointer;
}
button {
margin: 2px;
padding: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>MongoDB CRUD Application</h2>

<!-- Form to Add/Edit Records -->


<form id="recordForm">
<input type="hidden" id="recordId">
<label for="name">Name:</label>
<input type="text" id="name" required>
<label for="age">Age:</label>
<input type="number" id="age" required>
<button type="submit">Save</button>
</form>

<!-- Table to Display Records -->


<table>
<thead>
<tr>
<th>Name</th>

<thonclick="toggleSort()">Age ⬍</th><!-- Sortable column -->


<th>Actions</th>
</tr>
</thead>
<tbody id="recordsTableBody"></tbody>
</table>

<script>
let records = [];
let sortAscending = true;

async function loadRecords() {


const res = await fetch('http://localhost:3000/records');
records = await res.json();
displayRecords();
}

function displayRecords() {
consttableBody = document.getElementById('recordsTableBody');
tableBody.innerHTML = '';

constsortedRecords = [...records].sort((a, b) =>


sortAscending ?a.age - b.age : b.age - a.age
);

sortedRecords.forEach(record => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.name}</td>
<td>${record.age}</td>
<td>
<button onclick="editRecord('${record._id}', '${record.name}', '${record.age}')">Edit</button>
<button onclick="deleteRecord('${record._id}')">Delete</button>
</td>
`;
tableBody.appendChild(row);
});
}

function toggleSort() {
sortAscending= !sortAscending;
displayRecords();
}

document.getElementById('recordForm').addEventListener('submit', async (e) => {


e.preventDefault();
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
constrecordId = document.getElementById('recordId').value;

if (recordId) {
await fetch(`http://localhost:3000/update/${recordId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, age })
});
} else {
await fetch('http://localhost:3000/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, age })
});
}

document.getElementById('recordForm').reset();
document.getElementById('recordId').value = '';
loadRecords();
});

async function deleteRecord(id) {


await fetch(`http://localhost:3000/delete/${id}`, { method: 'DELETE' });
loadRecords();
}

function editRecord(id, name, age) {


document.getElementById('name').value = name;
document.getElementById('age').value = age;
document.getElementById('recordId').value = id;
}

loadRecords();
</script>
</body>
</html>
Server.js
// server.js (Backend)
const express = require('express');
const mongoose = require('mongoose');
constbodyParser = require('body-parser');
constcors = require('cors');

const app = express();


app.use(cors());
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/simpleApp', {
useNewUrlParser: true,
useUnifiedTopology: true,
});

constRecordSchema = new mongoose.Schema({


name: String,
age: Number,
});

const Record = mongoose.model('Record', RecordSchema);

// Add a new record


app.post('/add', async (req, res) => {
constnewRecord = new Record(req.body);
await newRecord.save();
res.json({ message: 'Record added successfully' });
});

// Get all records


app.get('/records', async (req, res) => {
const records = await Record.find();
res.json(records);
});

// Update record by ID
app.put('/update/:id', async (req, res) => {
await Record.findByIdAndUpdate(req.params.id, req.body);
res.json({ message: 'Record updated successfully' });
});

// Delete record by ID
app.delete('/delete/:id', async (req, res) => {
await Record.findByIdAndDelete(req.params.id);
res.json({ message: 'Record deleted successfully' });
});

app.listen(3000, () => console.log('Server running on port 3000'));

Output:

You might also like