-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
113 lines (102 loc) · 2.43 KB
/
Copy pathapp.js
File metadata and controls
113 lines (102 loc) · 2.43 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
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
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const twig = require('twig');
const app = express();
const MONGODB_URL = 'mongodb://localhost:27017/mongoose';
const Post = require('./models/post');
// SET VIEW ENGINE and VIEWS
app.set('view engine', 'html');
app.engine('html', twig.__express);
app.set('views','views');
// APPLY BODY-PARSER MIDDLEWARE
app.use(bodyParser.urlencoded({extended:false}));
// HOME PAGE
app.get('/', (req, res) => {
// FETCH ALL POST FROM DATABASE
Post.find()
// SET descending ORDER BY createdAt
.sort({createdAt: 'descending'})
.then(result => {
if(result){
// RENDERING HOME VIEW WITH ALL POST
res.render('home',{
allpost:result
});
}
})
.catch(err => {
if (err) throw err;
});
});
// INSERT POST
app.post('/', (req, res) => {
new Post({
title:req.body.title,
content:req.body.content,
author_name:req.body.author
})
.save()
.then(result => {
res.redirect('/');
})
.catch(err => {
if (err) throw err;
});
});
// EDIT POST
app.get('/edit/:id', (req, res) => {
Post.findById(req.params.id)
.then(result => {
if(result){
res.render('edit',{
post:result
});
}
else{
res.redirect('/');
}
})
.catch(err => {
res.redirect('/');
});
});
// UPDATE POST
app.post('/edit/:id', (req, res) => {
Post.findById(req.params.id)
.then(result => {
if(result){
result.title = req.body.title;
result.content = req.body.content;
result.author_name = req.body.author;
return result.save();
}
else{
console.log(err);
res.redirect('/');
}
})
.then(update => {
res.redirect('/');
})
.catch(err => {
res.redirect('/');
});
});
// DELETE POST
app.get('/delete/:id', (req, res) => {
Post.findByIdAndDelete(req.params.id)
.then(result => {
res.redirect('/');
})
.catch(err => {
console.log(err);
res.redirect('/');
})
});
// IF DATABASE CONNECTION IS SUCCESSFULLY THEN RUN APP on PORT 3000
mongoose.connect(MONGODB_URL, {useNewUrlParser: true}).then(result => {
app.listen(3000);
}).catch(err => {
if (err) throw err;
});