-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
97 lines (80 loc) · 1.97 KB
/
server.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
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const exphbs = require('express-handlebars');
const methodOverride = require('method-override');
const app = express();
const db = require('./config/keys').mongoURI;
// Connecting to MongoDB database
mongoose
.connect(db)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
// Body parser Middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
// Handlebars Middleware
app.engine('handlebars', exphbs({
defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
// Method Override Middleware
app.use(methodOverride('_method'));
const port = 3000;
// Listening
app.listen(3000, () => {
console.log(`Server running on port ${port}...`)
});
// Quote model
const Quote = require('./models/Quote');
// Get all quotes
app.get('/', (req, res) => {
Quote.find({})
.then(quotes => {
res.render('index', {quotes: quotes})
})
});
// Get edit form
app.get('/edit/:id', (req, res) => {
Quote.findOne({
_id: req.params.id
})
.then(quote => {
res.render('edit', {
quote: quote
})
})
});
// Add a quote
app.post('/quotes', (req, res) => {
//Creating new quote
const newQuote = new Quote({
name: req.body.name,
quote: req.body.quote
});
// Save quote
new Quote(newQuote).save()
.then(res.redirect('/'));
});
// Edit a quote
app.put('/quotes/:id', (req, res) => {
Quote.findOne({
_id: req.params.id
})
.then(quote => {
// new values
quote.name = req.body.name;
quote.quote = req.body.quote;
quote.save()
.then(() => {
res.redirect('/');
})
});
});
// Delete a quote
app.delete('/quotes/:id', (req, res) => {
Quote.remove({_id: req.params.id})
.then(() => {
res.redirect('/');
});
});