-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
80 lines (71 loc) · 2.58 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
const express = require('express');
const bodyParser = require('body-parser')
const app = express();
const MongoClient = require('mongodb').MongoClient
const connectionString = process.env.MONGO_URI;
// const connectionString = 'mongodb+srv://<username>:<password>@cluster0.3dodw.mongodb.net/<dbname>?retryWrites=true&w=majority'
MongoClient.connect(connectionString, { useUnifiedTopology: true})
.then(client => {
console.log('Connected to Database')
const db = client.db('star-wars-quotes')
const quotesCollection = db.collection('quotes')
//Middlewares
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(express.static('public'))
//Routes
app.get('/', (req, res) => {
const cursor = db.collection('quotes').find().toArray()
.then(results => {
res.render('index.ejs', { quotes: results})
})
.catch(error => console.error(error))
})
app.post('/quotes', (req, res) => {
quotesCollection.insertOne(req.body)
.then(result => {
res.redirect('/')
console.log('Quote added.')
})
.catch(error => console.error(error))
})
app.put('/quotes', (req, res) => {
quotesCollection.findOneAndUpdate(
{ name: 'yoda'},
{
$set: {
name: req.body.name,
quote: req.body.quote
}
},
{
upsert: true
}
)
.then(result => {
console.log('Qupte updated.')
res.json('Success')
})
.catch(error => {
console.error(error)
})
})
app.delete('/quotes', (req, res) => {
quotesCollection.deleteOne(
{ name: req.body.name}
)
.then(result => {
if (result.deletedCount == 0) {
return res.json('No quote to delete')
}
res.json('Deleted quote')
})
.catch(error => console.error(error))
})
//Listening
app.listen(process.env.PORT || 3000, function() {
console.log('listening on 3000')
})
})
.catch(error => console.error(error))