-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
68 lines (55 loc) · 1.61 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
const express = require('express')
const app = express()
const bodyParser= require('body-parser')
const MongoClient = require('mongodb').MongoClient
var db
MongoClient.connect('mongodb://flocktest1:[email protected]:45148/flocktest1', (err, database) => {
// ... start the server
if (err) return console.log(err)
db = database
app.listen(3000, () => {
console.log('listening on 3000')
})
})
// mongodb://<dbuser>:<dbpassword>@ds145148.mlab.com:45148/flocktest1
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.static('public'))
// All your handlers here...
app.get('/', (req, res) => {
db.collection('quotes').find().toArray((err, result) => {
if (err) return console.log(err)
// renders index.ejs
res.render('index.ejs', {quotes: result})
})
})
app.post('/quotes', (req, res) => {
db.collection('quotes').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
})
app.put('/quotes', (req, res) => {
db.collection('quotes')
.findOneAndUpdate({name: 'Audrey'}, {
$set: {
name: req.body.name,
quote: req.body.quote
}
}, {
sort: {_id: -1},
upsert: true
}, (err, result) => {
if (err) return res.send(err)
res.send(result)
})
})
app.delete('/quotes', (req, res) => {
db.collection('quotes').findOneAndDelete({name: req.body.name},
(err, result) => {
if (err) return res.send(500, err)
res.json('A darth vadar quote got deleted')
})
})
})