Lecture Notes Of Day 30: Project Development (MongoDB Final Project)

Rashmi Mishra
0

 

Lecture Notes Of Day 30
Project Development (MongoDB Final Project)

Objective:

The goal of this session is to help students apply all the knowledge they have gained throughout the course to develop a real-world application using MongoDB. This session will focus on creating a full-stack application, integrating MongoDB with both frontend and backend technologies.

Outcome:

By the end of the session, students will:

  • Have hands-on experience designing and implementing a real-world MongoDB application.
  • Understand how to use MongoDB as the backend database in a full-stack application.
  • Gain experience in integrating MongoDB with both frontend and backend technologies.
  • Learn best practices for working with databases, handling CRUD operations, and structuring applications.

1. Introduction to MongoDB and the Project

MongoDB is a NoSQL database that allows for flexible data storage and scaling. It stores data in JSON-like format (BSON), making it easy to work with JavaScript and web technologies.

In this session, you will build a simple project that integrates MongoDB into both the backend and frontend. This will demonstrate how to use MongoDB for data storage, create API endpoints to interact with the database, and render data on the frontend.


2. Choosing a Project Idea

Before we dive into the technical implementation, we need to decide on a project idea. Some example project ideas using MongoDB:

  • Task Management Application: A web app where users can create, view, update, and delete tasks.
  • Blog Platform: A blogging platform where users can create, read, update, and delete blog posts.
  • Product Inventory System: An inventory management system where users can track products, manage stock, and view sales.

In this session, we'll walk through creating a simple Task Management Application, where users can perform CRUD (Create, Read, Update, Delete) operations on tasks.


3. Setting Up MongoDB

3.1 Install MongoDB

First, ensure that MongoDB is installed on your local machine or you can use a cloud service like MongoDB Atlas. To install MongoDB locally, follow the official MongoDB installation guide.

3.2 Connect MongoDB Database

Once MongoDB is installed, connect to the database using the MongoDB shell or a database client like MongoDB Compass. In this case, we'll be using MongoDB with Node.js and Express.

For the cloud option, you can create a free cluster on MongoDB Atlas and get a connection string.


4. Backend Setup: Node.js and Express

The backend will be built using Node.js and Express. This allows us to easily create a server that can handle HTTP requests and interact with MongoDB.

4.1 Initialize the Project

1.   Create a new directory for your project and navigate into it.

mkdir task-management-app

cd task-management-app

2.   Initialize a new Node.js project.

npm init -y

3.   Install necessary packages:

npm install express mongoose body-parser

  • express: Web framework for Node.js.
  • mongoose: ODM (Object Data Modeling) library for MongoDB and Node.js.
  • body-parser: Middleware to parse incoming request bodies.

4.2 Create Server File (server.js)

Create a server.js file where we’ll set up the Express server and connect to MongoDB.

const express = require('express');

const mongoose = require('mongoose');

const bodyParser = require('body-parser');

const app = express();

// Middleware

app.use(bodyParser.json());

// MongoDB connection

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

  .then(() => console.log('Connected to MongoDB'))

  .catch(err => console.error('Could not connect to MongoDB', err));

// Define a Task model

const taskSchema = new mongoose.Schema({

  title: String,

  description: String,

  completed: Boolean

});

const Task = mongoose.model('Task', taskSchema);

// Routes for CRUD operations

// Create a task

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);

});

// Read all tasks

app.get('/tasks', async (req, res) => {

  const tasks = await Task.find();

  res.send(tasks);

});

// 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);

});

// Delete a task

app.delete('/tasks/:id', async (req, res) => {

  await Task.findByIdAndDelete(req.params.id);

  res.send({ message: 'Task deleted' });

});

// Start the server

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

4.3 Run the Backend Server

Start the backend server using the command:

node server.js

You can test the API using Postman or curl to send requests to the backend.


5. Frontend Setup

In this example, we will use HTML, CSS, and JavaScript to build the frontend. You can also use libraries like React for a more interactive interface.

5.1 Create Frontend Files

1.   Create an index.html file for the user interface.

2.   Add CSS for basic styling.

3.   Use JavaScript to interact with the backend API.

5.2 Basic HTML Structure

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Task Management</title>

  <link rel="stylesheet" href="styles.css">

</head>

<body>

  <h1>Task Management</h1>

  <div>

    <input type="text" id="task-title" placeholder="Enter Task Title">

    <input type="text" id="task-desc" placeholder="Enter Task Description">

    <button onclick="addTask()">Add Task</button>

  </div>

  <h2>Tasks List</h2>

  <ul id="tasks-list"></ul>

  <script src="script.js"></script>

</body>

</html>

5.3 Add JavaScript for API Interaction

const apiUrl = 'http://localhost:3000/tasks';

// Fetch and display tasks

async function fetchTasks() {

  const response = await fetch(apiUrl);

  const tasks = await response.json();

  const tasksList = document.getElementById('tasks-list');

  tasksList.innerHTML = '';

  tasks.forEach(task => {

    const li = document.createElement('li');

    li.innerHTML = `${task.title} - ${task.description} - Completed: ${task.completed}`;

    tasksList.appendChild(li);

  });

}

// Add a new task

async function addTask() {

  const title = document.getElementById('task-title').value;

  const description = document.getElementById('task-desc').value;

  const response = await fetch(apiUrl, {

    method: 'POST',

    headers: { 'Content-Type': 'application/json' },

    body: JSON.stringify({ title, description })

  });

  const task = await response.json();

  fetchTasks();

}

// Load tasks on page load

window.onload = fetchTasks;


6. Running the Full Application

1.   Ensure MongoDB is running.

2.   Run the backend server using node server.js.

3.   Open index.html in a browser to interact with the frontend.

4.   You can now add tasks, view them, and perform CRUD operations.


7. Conclusion and Next Steps

In this session, you've built a simple Task Management Application using MongoDB, Node.js, and Express. You've learned how to:

  • Set up a MongoDB database.
  • Build backend API endpoints to perform CRUD operations.
  • Create a basic frontend to interact with the backend.

For further improvement, you can:

  • Enhance the frontend using React for dynamic rendering.
  • Add authentication using JWT.
  • Deploy the application to a cloud platform like Heroku.

This hands-on project helps solidify your understanding of MongoDB and its integration into full-stack development.



Tags

Post a Comment

0Comments

Post a Comment (0)

About Me