-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
134 lines (94 loc) · 2.51 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
let express = require("express"),
bodyParser = require('body-parser'),
mongoose = require('mongoose')
methodOverride = require('method-override');
const expressSanitizer = require('express-sanitizer');
let app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.use(express.static('public'));
app.use(methodOverride('_method'));
app.use(expressSanitizer());
const Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/blogapp', { useNewUrlParser: true, useUnifiedTopology: true } );
const blogappSchema = new Schema({
name: {type: String},
image: {type: String},
body: {type: String},
dateCreated: {type: Date, default: Date.now}
});
const blogapp = mongoose.model("blogapp", blogappSchema);
/*
blogapp.create({
name: "Test dog blogpost",
image: "https://images.pexels.com/photos/406014/pexels-photo-406014.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=200&w=300",
body: "Hi, this is the first dog blogpost"
});
*/
app.get('/', (req, res) => {
res.redirect('/blogs');
});
app.get('/blogs', (req, res) => {
blogapp.find({}, (err, blogs) => {
if (err) {
console.log(err);
} else {
res.render("index", {blogs: blogs});
}
});
});
app.get('/blogs/new', (req, res) => {
res.render("new");
});
app.get('/blogs/:id', (req, res) => {
blogapp.findById(req.params.id, (err, foundblog) =>{
if (err) {
res.redirect('/blogs');
} else {
res.render("show", {foundblog: foundblog});
}
})
});
app.get('/blogs/:id/edit', (req, res) => {
blogapp.findById(req.params.id, (err, foundblog) =>{
if (err) {
res.redirect('/blogs');
} else {
res.render("edit", {foundblog: foundblog});
}
})
});
app.post('/blogs', (req, res) => {
req.body.blog.body = req.sanitize(req.body.blog.body);
blogapp.create(req.body.blog, function (err, blogs) {
if (err) {
res.render("new");
} else {
res.redirect('/blogs');
}
});
});
app.put('/blogs/:id', (req, res) => {
req.body.blog.body = req.sanitize(req.body.blog.body);
blogapp.findByIdAndUpdate(req.params.id, req.body.blog, function (err, updatedblog) {
if (err) {
res.redirect('/blogs');
} else {
res.redirect('/blogs/'+ req.params.id);
}
}
);
});
app.delete('/blogs/:id', (req, res) => {
blogapp.findByIdAndRemove(req.params.id, function (err, updatedblog) {
if (err) {
res.redirect('/blogs');
} else {
res.redirect('/blogs');
}
}
);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});