-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
122 lines (105 loc) · 2.35 KB
/
app.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://127.0.0.1:27017/newDB");
const schema = new mongoose.Schema({
id: String,
name: String,
age: Number,
skill: [String],
graduationThreshold: {
service: Boolean,
english: Boolean,
information: Boolean,
},
gQualification: Boolean,
});
const Student = mongoose.model("Student", schema);
app.get("/", (req, res) => {
res.send("this is homepage");
});
//get all student data
app.get("/students", async (req, res) => {
await Student.find({})
.then((data) => {
res.send(data);
})
.catch((e) => {
res.send(e);
});
});
//add new student data
app.post("/students", (req, res) => {
const { id, name, age, skill, service, english, information } = req.body;
const qQualification = null;
if (service && english && information) {
gQualification = true;
} else {
gQualification = false;
}
const student = new Student({
id: id,
name: name,
age: age,
skill: skill,
graduationThreshold: {
service: service,
english: english,
information: information,
},
gQualification: gQualification,
});
student
.save()
.then((data) => {
res.send(data);
})
.catch((e) => {
res.send(e);
});
});
//delete student data
app.delete("/students/:id", (req, res) => {
const { id } = req.params;
console.log(id);
try {
Student.deleteOne({ id }).then((msg) => {
res.send(msg);
});
} catch (e) {
res.send(e);
}
});
class newData {
constructor() {}
setData(key, value) {
if (key !== "service" && key !== "english" && key !== "information") {
this[key] = value;
} else {
this[`graduationThreshold.${key}`] = value;
}
}
}
//update data use patch method
app.patch("/students/:id", async (req, res) => {
const { id } = req.params;
const newItem = new newData();
for (let i in req.body) {
newItem.setData(i, req.body[i]);
}
Student.findOneAndUpdate({ id: id }, newItem, {
new: true,
runValidators: true,
})
.then((msg) => {
res.send("Success update")
})
.catch((e) => {
console.log(e);
});
});
app.listen(3030, () => {
console.log("server runnning in 3030");
});