Find a time app
1. Setup Instructions
Prerequisites:
- Install Node.js.
sudo apt updatesudo apt install -y nodejs npm - Install MongoDB and ensure it is running locally or on a server.
https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/
Create a New Project:
- Create a directory for your project:
mkdir nodejs-mongodb-examplecd nodejs-mongodb-example - Initialize a Node.js project:
npm init -y - Install the required dependencies:
npm install express mongodb body-parser ejs
2. Directory Structure
Here’s how the project will be organized:
nodejs-mongodb-example/
│
├── public/
│ └── styles.css
│
├── views/
│ ├── index.ejs
│ ├── add.ejs
│ └── edit.ejs
│
├── app.js
└── package.json
3. Code
(a) app.js
This is the main Node.js application file.
const express = require('express');
const bodyParser = require('body-parser');
const { MongoClient, ObjectId } = require('mongodb');
const app = express();
const url = 'mongodb://localhost:27017';
const dbName = 'exampleDB';
let db;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.set('view engine', 'ejs');
// Connect to MongoDB
MongoClient.connect(url, { useUnifiedTopology: true })
.then(client => {
console.log('Connected to MongoDB');
db = client.db(dbName);
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
})
.catch(err => console.error(err));
// Routes
// Home Page - Display All Entries
app.get('/', async (req, res) => {
const items = await db.collection('entries').find().toArray();
res.render('index', { items });
});
// Add Entry Page
app.get('/add', (req, res) => {
res.render('add');
});
// Handle Add Entry
app.post('/add', async (req, res) => {
const { name, age } = req.body;
await db.collection('entries').insertOne({ name, age: parseInt(age, 10) });
res.redirect('/');
});
// Edit Entry Page
app.get('/edit/:id', async (req, res) => {
const item = await db.collection('entries').findOne({ _id: ObjectId(req.params.id) });
res.render('edit', { item });
});
// Handle Edit Entry
app.post('/edit/:id', async (req, res) => {
const { name, age } = req.body;
await db.collection('entries').updateOne(
{ _id: ObjectId(req.params.id) },
{ $set: { name, age: parseInt(age, 10) } }
);
res.redirect('/');
});
// Handle Delete Entry
app.post('/delete/:id', async (req, res) => {
await db.collection('entries').deleteOne({ _id: ObjectId(req.params.id) });
res.redirect('/');
});
(b) Views
index.ejs
The homepage showing all entries.
<!DOCTYPE html>
<html>
<head>
<title>MongoDB Example</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Entries</h1>
<a href="/add">Add New Entry</a>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<% items.forEach(item => { %>
<tr>
<td><%= item.name %></td>
<td><%= item.age %></td>
<td>
<a href="/edit/<%= item._id %>">Edit</a>
<form action="/delete/<%= item._id %>" method="POST" style="display:inline;">
<button type="submit">Delete</button>
</form>
</td>
</tr>
<% }) %>
</tbody>
</table>
</body>
</html>
add.ejs
Form to add a new entry.
<!DOCTYPE html>
<html>
<head>
<title>Add Entry</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Add Entry</h1>
<form action="/add" method="POST">
<label>Name:</label>
<input type="text" name="name" required>
<label>Age:</label>
<input type="number" name="age" required>
<button type="submit">Add</button>
</form>
<a href="/">Back to Home</a>
</body>
</html>
edit.ejs
Form to edit an existing entry.
<!DOCTYPE html>
<html>
<head>
<title>Edit Entry</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Edit Entry</h1>
<form action="/edit/<%= item._id %>" method="POST">
<label>Name:</label>
<input type="text" name="name" value="<%= item.name %>" required>
<label>Age:</label>
<input type="number" name="age" value="<%= item.age %>" required>
<button type="submit">Update</button>
</form>
<a href="/">Back to Home</a>
</body>
</html>
(c) Public Styles
Create a styles.css file in the public/ directory:
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #333;
}
table {
width: 100%;
border-collapse: collapse;
}
table th, table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
table th {
background-color: #f4f4f4;
}
form {
display: inline;
}
button {
background-color: #007BFF;
color: #fff;
border: none;
padding: 5px 10px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
a {
color: #007BFF;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
4. Running the Application
- Start your MongoDB server.
- Run the Node.js application:
node app.js - Open your browser and navigate to http://localhost:3000.
5. Examining the Database
mongosh
use meeting_app
db.meetings.find().pretty()
