-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
101 lines (84 loc) · 2.69 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
const express = require("express")
const bodyparse = require("body-parser")
PORT=3000
const mongoose = require("mongoose")
const app = express();
app.use(bodyparse.urlencoded({
extended: true
}));
app.use(express.json());
mongoose.connect("mongodb://localhost:27017/courseDB", {useNewUrlParser: true});
// creting schema
const courseSchema ={
id:Number,
courseName:String,
courseType:String,
courseDuration:String,
courseRating:Number
};
// creating model
const Course = mongoose.model("Course",courseSchema);
// chained route handlers
app.route("/courses")
.get(function(req,res){
Course.find({},function(err,foundCourses){
if(!err){
res.send(foundCourses)
} else{
res.send(err)
}
})
})
.post(function(req,res){
const newCourse = new Course({
id:parseInt(req.body.id),
courseName:req.body.courseName,
courseType:req.body.courseType,
courseDuration:req.body.courseDuration,
courseRating:parseInt(req.body.courseRating)
});
// saving newLy added data to mongoDB
newCourse.save(function(err){
if(!err){
res.send("Successfully added a new courseSchema.");
} else{
res.send(err);
}
})
})
.delete(function(req,res){
Course.deleteMany(function(err){
if(!err){
res.send("Successfully deleted all courses.")
} else{
res.send(err)
}
})
});
// for getting particular courses details
app.route("/courses/:courseDetails")
// for getting course details of particular id
.get(function(req,res){
Course.findOne({id:req.params.courseDetails},function(err,foundCourse){
if(foundCourse && !err){
res.send(foundCourse)
} else {
res.send("No data found with given id")
}
});
})
// update all data for particular course id
.put(function(req,res){
Course.updateMany(
{id: parseInt(req.params.courseDetails)},
{id: parseInt(req.body.id), courseName: req.body.courseName, courseType: req.body.courseType, courseDuration: req.body.courseDuration, courseRating:parseInt(req.body.courseRating)},
function(err){
if(!err){
res.send(" Successfully update all fields.");
}
}
);
});
app.listen(PORT,function(){
console.log("Server started on port 3000")
});