Assignments Of Day 30
Project Development (MongoDB Final Project)
Assignment 1: Set Up MongoDB and Node.js Environment
Task:
1. Install MongoDB on your local machine or create a cloud database using MongoDB Atlas.
2. Install Node.js and Express.
3. Set up a basic Express server.
Step-by-Step Solution:
1. Install MongoDB:
o For Local Installation: Follow the instructions on the MongoDB installation page.
o Using MongoDB Atlas: Go to MongoDB Atlas, sign up, and create a free cluster.
2. Install Node.js:
o Download and install Node.js from nodejs.org.
o To check if it’s installed, run node -v in the terminal.
3. Set Up Express Server:
o Initialize a new project:
mkdir task-app
cd task-app
npm init -y
o Install Express:
npm install express
o Create server.js:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Server running on port ${port}`));
o Run the server using node server.js.
Assignment 2: Create a MongoDB Database and Collection
Task:
1. Create a database called taskdb in MongoDB.
2. Create a collection named tasks with sample documents.
Step-by-Step Solution:
1. Connect to MongoDB:
o In MongoDB Compass or through the shell, connect to your database server.
2. Create Database:
o Use the following command in MongoDB shell:
use taskdb
3. Create Collection and Insert Documents:
o Insert a sample document into the tasks collection:
db.tasks.insertOne({
title: "Complete Assignment",
description: "Finish MongoDB assignment for class",
completed: false
})
4. Verify the Collection:
o Run db.tasks.find() to view all inserted documents.
Assignment 3: Implement a POST API to Add Tasks
Task:
1. Create an API endpoint to add a task to the MongoDB collection.
Step-by-Step Solution:
1. Set Up Mongoose:
o Install Mongoose in your Node.js project:
npm install mongoose
2. Connect to MongoDB:
o In server.js, connect to MongoDB using Mongoose:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/taskdb', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('Failed to connect to MongoDB', err));
3. Create Task Model:
o Define a schema for tasks:
const taskSchema = new mongoose.Schema({
title: String,
description: String,
completed: Boolean
});
const Task = mongoose.model('Task', taskSchema);
4. Create POST API:
o Create an endpoint to add tasks:
app.post('/tasks', async (req, res) => {
const task = new Task({
title: req.body.title,
description: req.body.description,
completed: false
});
await task.save();
res.send(task);
});
5. Test the POST API:
o Use Postman or curl to test the endpoint by sending a POST request with the task data.
Assignment 4: Implement a GET API to Fetch All Tasks
Task:
1. Create an API endpoint to fetch all tasks from MongoDB.
Step-by-Step Solution:
1. Create GET API:
o In server.js, create a route to get all tasks:
app.get('/tasks', async (req, res) => {
const tasks = await Task.find();
res.send(tasks);
});
2. Test the GET API:
o Use Postman or curl to test the endpoint by sending a GET request.
Assignment 5: Implement a PUT API to Update a Task
Task:
1. Create an API endpoint to update a specific task by its ID.
Step-by-Step Solution:
1. Create PUT API:
o In server.js, create a route to update a task:
app.put('/tasks/:id', async (req, res) => {
const task = await Task.findByIdAndUpdate(
req.params.id,
{ title: req.body.title, description: req.body.description, completed: req.body.completed },
{ new: true }
);
res.send(task);
});
2. Test the PUT API:
o Use Postman to send a PUT request to update the task by its ID.
Assignment 6: Implement a DELETE API to Remove a Task
Task:
1. Create an API endpoint to delete a specific task by its ID.
Step-by-Step Solution:
1. Create DELETE API:
o In server.js, create a route to delete a task:
app.delete('/tasks/:id', async (req, res) => {
await Task.findByIdAndDelete(req.params.id);
res.send({ message: 'Task deleted' });
});
2. Test the DELETE API:
o Use Postman to send a DELETE request to remove a task by its ID.
Assignment 7: Implement Frontend to Add Tasks
Task:
1. Create a simple HTML form to add tasks.
2. Use JavaScript to send the task data to the backend API.
Step-by-Step Solution:
1. Create HTML Form:
o Create a form with two fields: title and description for the task.
<form id="task-form">
<input type="text" id="task-title" placeholder="Task Title" required>
<input type="text" id="task-desc" placeholder="Task Description" required>
<button type="submit">Add Task</button>
</form>
2. Add JavaScript to Handle Form Submission:
document.getElementById('task-form').addEventListener('submit', async (e) => {
e.preventDefault();
const title = document.getElementById('task-title').value;
const description = document.getElementById('task-desc').value;
const response = await fetch('http://localhost:3000/tasks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, description })
});
const task = await response.json();
console.log('Task Added:', task);
});
Assignment 8: Display All Tasks on Frontend
Task:
1. Fetch and display all tasks from the backend API on the frontend.
Step-by-Step Solution:
1. Fetch and Display Tasks:
async function fetchTasks() {
const response = await fetch('http://localhost:3000/tasks');
const tasks = await response.json();
const tasksList = document.getElementById('tasks-list');
tasksList.innerHTML = '';
tasks.forEach((task) => {
const li = document.createElement('li');
li.textContent = `${task.title} - ${task.description}`;
tasksList.appendChild(li);
});
}
window.onload = fetchTasks;
Assignment 9: Implement Task Filtering
Task:
1. Create a filter option on the frontend to view only completed tasks.
Step-by-Step Solution:
1. Add a Filter:
o Add a checkbox to filter completed tasks.
<label>
Show Completed Tasks Only:
<input type="checkbox" id="filter-completed">
</label>
2. Modify Fetch Logic:
document.getElementById('filter-completed').addEventListener('change', fetchTasks);
async function fetchTasks() {
const filter = document.getElementById('filter-completed').checked;
const response = await fetch(`http://localhost:3000/tasks?completed=${filter}`);
const tasks = await response.json();
const tasksList = document.getElementById('tasks-list');
tasksList.innerHTML = '';
tasks.forEach((task) => {
const li = document.createElement('li');
li.textContent = `${task.title} - ${task.description}`;
tasksList.appendChild(li);
});
}
Assignment 10: Implement Task Search
Task:
1. Implement a search functionality to find tasks based on the title.
Step-by-Step Solution:
1. Add Search Input:
<input type="text" id="search-input" placeholder="Search Tasks" />
2. Modify Fetch Logic:
document.getElementById('search-input').addEventListener('input', fetchTasks);
async function fetchTasks() {
const searchTerm = document.getElementById('search-input').value;
const response = await fetch(`http://localhost:3000/tasks?title=${searchTerm}`);
const tasks = await response.json();
const tasksList = document.getElementById('tasks-list');
tasksList.innerHTML = '';
tasks.forEach((task) => {
const li = document.createElement('li');
li.textContent = `${task.title} - ${task.description}`;
tasksList.appendChild(li);
});
}
