Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
87 lines (66 loc) · 1.8 KB
/
Copy pathserver.js
File metadata and controls
87 lines (66 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
require("dotenv").config();
const express = require("express");
const { MongoClient, ObjectId } = require("mongodb");
const app = express();
const PORT = process.env.PORT || 3000;
const url = process.env.MONGODB_URI;
const client = new MongoClient(url);
app.use(express.json());
app.use(express.static("public"));
let students;
async function startServer() {
try {
await client.connect();
console.log("MongoDB connected successfully! ✅");
const db = client.db("studentDB");
students = db.collection("students");
app.listen(PORT, "0.0.0.0", () => {
console.log(`Website running at http://localhost:${PORT}`);
});
} catch (error) {
console.log("Error ❌");
console.log(error);
}
}
// ADD STUDENT
app.post("/students", async (req, res) => {
const student = {
name: req.body.name,
age: Number(req.body.age),
department: req.body.department,
};
const result = await students.insertOne(student);
res.json({
message: "Student added successfully! 🎓",
id: result.insertedId,
});
});
// GET ALL STUDENTS
app.get("/students", async (req, res) => {
const allStudents = await students.find().toArray();
res.json(allStudents);
});
// UPDATE STUDENT
app.put("/students/:id", async (req, res) => {
const id = req.params.id;
const updatedStudent = {
name: req.body.name,
age: Number(req.body.age),
department: req.body.department,
};
await students.updateOne({ _id: new ObjectId(id) }, { $set: updatedStudent });
res.json({
message: "Student updated successfully! ✏️",
});
});
// DELETE STUDENT
app.delete("/students/:id", async (req, res) => {
const id = req.params.id;
await students.deleteOne({
_id: new ObjectId(id),
});
res.json({
message: "Student deleted successfully! 🗑️",
});
});
startServer();