step-by-step guide to develop a Student Management System (SMS) using the MERN stack with MongoDB Atlas

Rashmi Mishra
0

 

step-by-step guide to develop a Student Management System (SMS) using the MERN stack with MongoDB Atlas


Step 1: Set Up Your Development Environment

1. Hardware Requirements

  • A computer with at least:
    • 8 GB RAM (recommended)
    • 20 GB free storage
    • Modern processor (Intel i5 or equivalent)

2. Software Installation

  • Install Node.js:
    • Download from Node.js (LTS version recommended).
    • Verify installation:

node -v

npm -v

  • Install Git:
    • Download from Git.
    • Verify installation:

git --version

  • Install Code Editor:
    • Install Visual Studio Code (VS Code) from VS Code.

3. MongoDB Atlas Setup

  • Go to MongoDB Atlas.
  • Create an account and log in.
  • Create a Cluster:
    • Choose a free shared cluster (suitable for development).
    • Select a cloud provider and region.
  • Set Up Database Access:
    • Create a user with a username and password.
    • Whitelist your IP address for database access.
  • Connect to the Cluster:
    • Get the connection string (e.g., mongodb+srv://<username>:<password>@cluster0.mongodb.net/student-management).
    • Replace <username> and <password> with your credentials.

Step 2: Initialize the MERN Stack Project

1. Create a Project Folder

mkdir student-management-system

cd student-management-system

2. Initialize a Node.js Project

npm init -y

3. Set Up a Git Repository

git init


Step 3: Backend Development (Node.js and Express)

1. Install Dependencies

npm install express mongoose cors dotenv body-parser

2. Create Folder Structure

student-management-system/

── backend/

   ── models/

   ── routes/

   ── config/

   ── server.js

── frontend/

3. Create a server.js File

const express = require('express');

const mongoose = require('mongoose');

const cors = require('cors');

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

require('dotenv').config(); 

const app = express();

const PORT = process.env.PORT || 5000; 

// Middleware

app.use(cors());

app.use(bodyParser.json()); 

// MongoDB Atlas Connection

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })

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

    .catch(err => console.error(err)); 

// Routes

app.use('/api/students', require('./routes/studentRoutes'));

 

// Start the server

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

4. Add Environment Variables

Create a .env file:

MONGO_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/student-management

5. Create Student Model

In backend/models/Student.js:


const mongoose = require('mongoose');

 const studentSchema = new mongoose.Schema({

    name: { type: String, required: true },

    email: { type: String, required: true, unique: true },

    age: { type: Number, required: true },

    course: { type: String, required: true }

}, { timestamps: true });

 

module.exports = mongoose.model('Student', studentSchema);

6. Create Routes

In backend/routes/studentRoutes.js:

const express = require('express');

const Student = require('../models/Student');

const router = express.Router();

 

// Get all students

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

    try {

        const students = await Student.find();

        res.status(200).json(students);

    } catch (err) {

        res.status(500).json({ error: err.message });

    }

});

 

// Add a student

router.post('/', async (req, res) => {

    try {

        const newStudent = new Student(req.body);

        await newStudent.save();

        res.status(201).json(newStudent);

    } catch (err) {

        res.status(400).json({ error: err.message });

    }

});

 

module.exports = router;


Step 4: Frontend Development (React)

1. Initialize React App

npx create-react-app frontend

cd frontend

2. Install Axios for API Calls

npm install axios

3. Create Folder Structure


frontend/src/

── components/

   ── StudentForm.js

   ── StudentList.js

── App.js

4. Create StudentForm Component

In frontend/src/components/StudentForm.js:

import React, { useState } from 'react';

import axios from 'axios';

 

const StudentForm = () => {

    const [student, setStudent] = useState({ name: '', email: '', age: '', course: '' });

 

    const handleChange = (e) => {

        const { name, value } = e.target;

        setStudent({ ...student, [name]: value });

    };

 

    const handleSubmit = async (e) => {

        e.preventDefault();

        try {

            await axios.post('http://localhost:5000/api/students', student);

            alert('Student added successfully');

        } catch (err) {

            console.error(err.message);

        }

    };

 

    return (

        <form onSubmit={handleSubmit}>

            <input name="name" placeholder="Name" onChange={handleChange} />

            <input name="email" placeholder="Email" onChange={handleChange} />

            <input name="age" placeholder="Age" type="number" onChange={handleChange} />

            <input name="course" placeholder="Course" onChange={handleChange} />

            <button type="submit">Add Student</button>

        </form>

    );

};

 

export default StudentForm;

5. Create StudentList Component

In frontend/src/components/StudentList.js:

import React, { useEffect, useState } from 'react';

import axios from 'axios'; 

const StudentList = () => {

    const [students, setStudents] = useState([]);

 

    useEffect(() => {

        const fetchStudents = async () => {

            try {

                const response = await axios.get('http://localhost:5000/api/students');

                setStudents(response.data);

            } catch (err) {

                console.error(err.message);

            }

        };

        fetchStudents();

    }, []);

 

    return (

        <ul>

            {students.map(student => (

                <li key={student._id}>{student.name} ({student.email})</li>

            ))}

        </ul>

    );

};

 

export default StudentList;


Step 5: Combine Components in App.js

In frontend/src/App.js:

import React from 'react';

import StudentForm from './components/StudentForm';

import StudentList from './components/StudentList';

 

function App() {

    return (

        <div>

            <h1>Student Management System</h1>

            <StudentForm />

            <StudentList />

        </div>

    );

}

 

export default App;


Step 6: Run the Application

1. Start the Backend

cd backend

node server.js

2. Start the Frontend

cd frontend

npm start


Step 7: Test and Deploy

  • Test Locally: Ensure all CRUD operations work correctly.
  • Deploy Backend: Use Heroku or Render.
  • Deploy Frontend: Use Netlify or Vercel.
  • Update MongoDB Atlas connection string to allow access from production environments.

 

Tags

Post a Comment

0Comments

Post a Comment (0)

About Me