-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·118 lines (101 loc) · 2.37 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
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');3
const bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
// Database Connection
mongoose.connect('mongodb://localhost/nodekb',{ useMongoClient: true });
let db = mongoose.connection;
// Initiate express framework
const app = express();
// Bring in Models
let Article = require('./models/article');
// Load View Engine
app.set('views', path.join(__dirname,'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'public')));
app.get('/', function(req,res){
Article.find({}, function(err,articles){
if (err) {
console.log(err)
}else{
res.render('index',{
title:'Article',
articles: articles
});
}
});
});
// View Single Page
app.get('/article/:id', function(req,res){
Article.findById(req.params.id,function(err,article){
res.render('article',{
article:article
});
});
});
// Add Article Page Heading
app.get('/articles/add', function(req,res){
res.render('add_article',{
title:'Add Article'
});
});
// Add Article Page Function
app.post('/articles/add', function(req,res){
let article = new Article();
article.title = req.body.title;
article.author= req.body.author;
article.body = req.body.body;
article.save(function(err){
if (err) {
console.log(err);
return
}else{
res.redirect('/');
}
})
console.log(req.body.title);
return;
});
// Edit Article Page
app.get('/article/edit/:id', function(req,res){
Article.findById(req.params.id,function(err,article){
res.render('edit_article',{
title :'Edit Article',
article:article
});
});
});
// Edit Article Page Function
app.post('/articles/edit/:id', function(req,res){
let article = {};
article.title = req.body.title;
article.author= req.body.author;
article.body = req.body.body;
let query = {_id:req.params.id}
Article.update(query,article, function(err){
if (err) {
console.log(err);
return
}else{
res.redirect('/');
}
})
console.log(req.body.title);
return;
});
//DELETE
app.delete('/article/:id', function(req, res){
let query = {_id:req.params.id}
Article.remove(query,function(err){
if (err) {
console.log(err);
}
res.send('Success');
})
})
app.listen(3000, function(){
console.log('Server Started');
})