to create the REST APIS in the node application
Creating a folder structure
Open image-20240422-093737.png
├── config/
└── db.js
├── models/
└── Student.js
├── routes/
└── studentRoutes.js
├── controllers/
└── studentController.js
├── app.js
└── package.json
app.js File
const express = require('express')
const app = express();
const Student = require('./models/student')
const mongoose = require('mongoose');
const studentRoutes = require('./routes/studentRoutes');
app.use(express.json())
app.use(express.static('public'));
// Routes
app.use('/students', studentRoutes);
mongoose.connect('*****') // MongoDB Connections
.then(() => {
console.log('Connected!');
app.listen(3000, () => {
console.group("server running on 3000")
})
})
.catch(() => {
console.log("connection failed !");
})
db.js file
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
async function connectToMongoDB() {
try {
await client.connect();
console.log("Connected to MongoDB");
} catch (err) {
console.error("Error connecting to MongoDB:", err);
}
}
connectToMongoDB();
controller file
// controllers/studentController.js
const Student = require('../models/Student');
exports.getAllStudents = async (req, res) => {
try {
const students = await Student.find();
res.json(students);
} catch (error) {
console.error('Error fetching students:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
exports.createStudent = async (req, res) => {
try {
const { name, age, grade } = req.body;
const newStudent = new Student({ name, age, grade });
await newStudent.save();
res.status(201).json(newStudent);
} catch (error) {
console.error('Error creating student:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
exports.getStudentById = async (req, res) => {
try {
const student = await Student.findById(req.params.id);
if (!student) {
return res.status(404).json({ message: 'Student not found' });
}
res.json(student);
} catch (error) {
console.error('Error fetching student:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
exports.deleteStudentById = async (req, res) => {
try {
const student = await Student.findByIdAndDelete(req.params.id);
if (!student) {
return res.status(404).json({ message: 'Student not found' });
}
res.json({ message: 'Student deleted successfully' });
} catch (error) {
console.error('Error deleting student:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
routes.js
// routes/studentRoutes.js
const express = require('express');
const router = express.Router();
const studentController = require('../controllers/studentController');
router.get('/', studentController.getAllStudents);
router.post('/', studentController.createStudent);
router.get('/:id', studentController.getStudentById);
router.delete('/:id', studentController.deleteStudentById);
module.exports = router;
model.js
// models/Student.js
const mongoose = require('mongoose'); // Correct import statement
const studentSchema = new mongoose.Schema({
name: String,
age: Number,
grade: String
});
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
Request Body can be send as
{
"name": "simple app",
"age": 20,
"grade": "A"
}
GET Request as / for getting all data from tale
POST Request as / to insert data to table
DELETE /id to delete a col from the table