Library Management System with Data Validation & Data Integrity
Aim
To design and implement a Library Management System using Node.js, Express.js, and MongoDB that enforces Data Validation and Data Integrity using Mongoose schema validation rules.
Software Requirements
- Node.js
- VS Code
- MongoDB
- Web Browser
Create the project folder and open it in VS Code. Final structure:
library-system/
│
├── server.js
├── package.json
│
└── public/
└── index.htmlnpm init -y
npm install express mongooseThis file contains the Book schema with strong validation rules and handles validation errors and duplicate ISBN (data integrity) professionally.
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = 5000;
app.use(express.json());
app.use(express.static('public'));
// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/libraryDB')
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
// ==============================
// Book Schema with Validation & Data Integrity
// ==============================
const bookSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'Book title is required'],
trim: true,
minlength: [3, 'Title must be at least 3 characters']
},
author: {
type: String,
required: [true, 'Author name is required'],
trim: true
},
isbn: {
type: String,
required: [true, 'ISBN is required'],
unique: true,
match: [/^[0-9]{10,13}$/, 'ISBN must be 10 or 13 digits']
},
category: {
type: String,
required: [true, 'Category is required'],
enum: {
values: ['Fiction', 'Non-Fiction', 'Science', 'Technology', 'History', 'Other'],
message: 'Category must be Fiction, Non-Fiction, Science, Technology, History or Other'
}
},
year: {
type: Number,
required: [true, 'Publication year is required'],
min: [1000, 'Year must be greater than 1000'],
max: [new Date().getFullYear(), 'Year cannot be in the future']
},
quantity: {
type: Number,
required: [true, 'Quantity is required'],
min: [0, 'Quantity cannot be negative'],
default: 1
},
available: {
type: Boolean,
default: true
}
}, { timestamps: true });
const Book = mongoose.model('Book', bookSchema);
// ==============================
// ROUTES
// ==============================
// Add New Book (with Validation)
app.post('/books', async (req, res) => {
try {
const book = new Book(req.body);
await book.save();
res.status(201).json({
message: 'Book added successfully',
book
});
} catch (error) {
// Handle Validation Errors
if (error.name === 'ValidationError') {
const errors = {};
Object.keys(error.errors).forEach(key => {
errors[key] = error.errors[key].message;
});
return res.status(400).json({
message: 'Validation Failed',
errors
});
}
// Handle Duplicate ISBN (Data Integrity)
if (error.code === 11000) {
return res.status(400).json({
message: 'Data Integrity Error',
error: 'ISBN already exists. Please use a unique ISBN.'
});
}
res.status(500).json({ message: 'Server Error', error: error.message });
}
});
// Get All Books
app.get('/books', async (req, res) => {
try {
const books = await Book.find().sort({ createdAt: -1 });
res.json(books);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Delete Book
app.delete('/books/:id', async (req, res) => {
try {
const book = await Book.findByIdAndDelete(req.params.id);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.json({ message: 'Book deleted successfully' });
} catch (error) {
res.status(500).json({ message: error.message });
}
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});The front-end form collects book details and displays clear validation error messages when data is invalid.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Library Management System</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: #f4f6f9;
color: #1a1a2e;
padding: 40px 20px;
}
.container { max-width: 800px; margin: 0 auto; }
header { text-align: center; margin-bottom: 35px; }
header h1 { font-size: 26px; margin-bottom: 6px; }
header p { color: #6b7280; font-size: 15px; }
.card {
background: white;
border-radius: 14px;
padding: 28px;
margin-bottom: 24px;
box-shadow: 0 4px 16px rgba(0,0,0,0.06);
}
.card h2 { font-size: 18px; margin-bottom: 18px; }
.form-group { margin-bottom: 16px; }
label { display: block; font-size: 14px; margin-bottom: 6px; color: #555; }
input, select {
width: 100%;
padding: 11px 14px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-size: 15px;
}
input:focus, select:focus {
outline: none;
border-color: #1e293b;
}
.btn {
background: #1e293b;
color: white;
border: none;
padding: 11px 20px;
border-radius: 8px;
font-size: 15px;
cursor: pointer;
}
.btn:hover { background: #0f172a; }
.btn-danger { background: #ef4444; }
.btn-danger:hover { background: #dc2626; }
.book-item {
background: #f8fafc;
padding: 16px;
border-radius: 10px;
margin-bottom: 12px;
border-left: 4px solid #1e293b;
}
.book-item h3 { margin-bottom: 6px; }
.book-meta { font-size: 13px; color: #6b7280; margin-bottom: 10px; }
#message {
padding: 12px 16px;
border-radius: 8px;
margin-bottom: 20px;
display: none;
}
.success { background: #d1fae5; color: #065f46; }
.error { background: #fee2e2; color: #991b1b; }
</style>
</head>
<body>
<div class="container">
<header>
<h1>Library Management System</h1>
<p>Data Validation & Data Integrity using Mongoose</p>
</header>
<div id="message"></div>
<div class="card">
<h2>Add New Book</h2>
<div class="form-group">
<label>Title *</label>
<input type="text" id="title" placeholder="Enter book title">
</div>
<div class="form-group">
<label>Author *</label>
<input type="text" id="author" placeholder="Enter author name">
</div>
<div class="form-group">
<label>ISBN * (10 or 13 digits)</label>
<input type="text" id="isbn" placeholder="Example: 9781234567890">
</div>
<div class="form-group">
<label>Category *</label>
<select id="category">
<option value="">Select Category</option>
<option value="Fiction">Fiction</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Science">Science</option>
<option value="Technology">Technology</option>
<option value="History">History</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group">
<label>Publication Year *</label>
<input type="number" id="year" placeholder="Example: 2023">
</div>
<div class="form-group">
<label>Quantity *</label>
<input type="number" id="quantity" placeholder="Example: 5" value="1">
</div>
<button class="btn" onclick="addBook()">Add Book</button>
</div>
<div class="card">
<h2>All Books</h2>
<div id="books"></div>
</div>
</div>
<script>
function showMessage(text, type) {
const msg = document.getElementById('message');
msg.innerText = text;
msg.className = type;
msg.style.display = 'block';
setTimeout(() => msg.style.display = 'none', 4000);
}
async function addBook() {
const data = {
title: document.getElementById('title').value.trim(),
author: document.getElementById('author').value.trim(),
isbn: document.getElementById('isbn').value.trim(),
category: document.getElementById('category').value,
year: Number(document.getElementById('year').value),
quantity: Number(document.getElementById('quantity').value)
};
try {
const res = await fetch('/books', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await res.json();
if (!res.ok) {
if (result.errors) {
const errorMessages = Object.values(result.errors).join('\\n');
showMessage(errorMessages, 'error');
} else {
showMessage(result.error || result.message, 'error');
}
return;
}
showMessage('Book added successfully!', 'success');
document.getElementById('title').value = '';
document.getElementById('author').value = '';
document.getElementById('isbn').value = '';
document.getElementById('category').value = '';
document.getElementById('year').value = '';
document.getElementById('quantity').value = '1';
loadBooks();
} catch (err) {
showMessage('Server error. Make sure backend is running.', 'error');
}
}
async function loadBooks() {
const res = await fetch('/books');
const books = await res.json();
const div = document.getElementById('books');
if (books.length === 0) {
div.innerHTML = '<p style="color:#6b7280">No books added yet.</p>';
return;
}
div.innerHTML = books.map(book => `
<div class="book-item">
<h3>${book.title}</h3>
<div class="book-meta">
Author: ${book.author} | ISBN: ${book.isbn} |
Category: ${book.category} | Year: ${book.year} |
Qty: ${book.quantity}
</div>
<button class="btn btn-danger" onclick="deleteBook('${book._id}')">Delete</button>
</div>
`).join('');
}
async function deleteBook(id) {
if (!confirm('Are you sure you want to delete this book?')) return;
await fetch(`/books/${id}`, { method: 'DELETE' });
showMessage('Book deleted successfully', 'success');
loadBooks();
}
loadBooks();
</script>
</body>
</html>node server.jsExpected output:
Server running at http://localhost:5000
Data Validation & Data Integrity Features
| Feature | Type | Purpose |
|---|---|---|
required |
Validation | Field cannot be empty |
minlength |
Validation | Title must have minimum characters |
match (Regex) |
Validation | ISBN must be 10 or 13 digits |
enum |
Validation | Category must be from allowed list |
min / max |
Validation | Year and Quantity range checking |
unique: true |
Data Integrity | ISBN cannot be duplicated |
trim: true |
Data Integrity | Removes extra spaces |
Result: The Library Management System successfully enforces Data Validation and Data Integrity using Mongoose schema rules. Invalid data is rejected with clear error messages, and duplicate ISBNs are prevented.






0 Ravula Kartheek:
Post a Comment