SP Ex-6
SP Ex-6
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>
<script>
let records = [];
let sortAscending = true;
function displayRecords() {
consttableBody = document.getElementById('recordsTableBody');
tableBody.innerHTML = '';
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();
}
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();
});
loadRecords();
</script>
</body>
</html>
Server.js
// server.js (Backend)
const express = require('express');
const mongoose = require('mongoose');
constbodyParser = require('body-parser');
constcors = require('cors');
mongoose.connect('mongodb://localhost:27017/simpleApp', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// 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' });
});
Output: