-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
147 lines (121 loc) · 2.63 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
//Connect to db
mongoose.connect('mongodb://localhost/tourapp');
let db = mongoose.connection;
//Check connection
db.once('open', function () {
console.log('Connected to DB');
});
//Check for DB errors
db.on('error', function (err) {
console.log(err);
});
//Import Models
let Tour = require('./models/tour');
//Init app
const app = express();
//load pug engine
app.set('views', "./views");
app.set('view engine', 'pug');
//Body-Parser
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//Public files
app.use(express.static('public'));
//home route
app.get('/', function (req, res) {
Tour.find({}, function (err, tours) {
if(err){
console.log(err);
} else {
res.render('index', {
title : 'Tours Page',
tours: tours
});
}
})
});
//add GET route
app.get('/tours/add', function (req, res) {
res.render('add_tour', {
title : "Add Tour"
});
})
//Get Single Tour
app.get('/tour/:id', function (req, res) {
Tour.findById(req.params.id, function (err, tour) {
if(err){
console.log(err);
} else {
res.render('tour', {
tour: tour
});
}
});
});
//Edit Tour form
app.get('/tour/edit/:id', function (req, res) {
Tour.findById(req.params.id, function (err, tour) {
if(err){
console.log(err);
} else {
res.render('edit_tour', {
title: "Edit Tour",
tour: tour
});
}
});
});
//Update Tour
app.post('/tours/edit/:id', function (req, res) {
let tour = {};
tour.title = req.body.title;
tour.company = req.body.company;
tour.body = req.body.body;
let query = {
_id: req.params.id
}
Tour.update(query, tour, function (err) {
if(err){
console.log(err);
return;
} else {
res.redirect('/');
}
});
});
//Delete Tour
app.delete('/tour/:id', function (req, res) {
let query = {_id : req.params.id};
Tour.deleteOne(query, function (err) {
if(err){
console.log(err);
} else {
res.send('Success');
}
});
});
//POST route
app.post('/tours/add', function (req, res) {
let tour = new Tour();
tour.title = req.body.title;
tour.company = req.body.company;
tour.body = req.body.body;
tour.save(function (err) {
if(err){
console.log(err);
return;
} else {
res.redirect('/');
}
});
});
//start server
app.listen(3000, function () {
console.log('server started on port 3000...');
})