-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
89 lines (75 loc) · 2.46 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
const express = require('express')
const app = express()
const MongoClient = require('mongodb').MongoClient
const PORT = process.env.PORT || 3000
require('dotenv').config()
let db,
dbConnectionStr = process.env.DB_STRING,
dbName = 'quotes'
MongoClient.connect(dbConnectionStr, { useUnifiedTopology: true })
.then(client => {
console.log(`Connected to ${dbName} Database`)
db = client.db(dbName)
})
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.get('/',(request, response)=>{
db.collection('motivational-quotes').find().sort({likes: -1}).toArray()
.then(data => {
response.render('index.ejs', { info: data })
})
.catch(error => console.error(error))
})
app.post('/addQuote', (request, response) => {
db.collection('motivational-quotes').insertOne({quoteName: request.body.quoteName,
authorName: request.body.authorName, likes: 0})
.then(result => {
console.log(request.body);
console.log('Quote Added')
response.redirect('/')
})
.catch(error => console.error(error))
})
app.put('/addOneLike', (request, response) => {
db.collection('motivational-quotes').updateOne({quoteName: request.body.quoteNameS, authorName: request.body.authorNameS,likes: request.body.likesS},{
$set: {
likes:request.body.likesS + 1
}
},{
sort: {_id: -1},
upsert: true
})
.then(result => {
console.log('Added One Like')
response.json('Like Added')
})
.catch(error => console.error(error))
})
app.put('/subOneLike', (request, response) => {
db.collection('motivational-quotes').updateOne({quoteName: request.body.quoteNameS, authorName: request.body.authorNameS,likes: request.body.likesS},{
$set: {
likes:request.body.likesS - 1
}
},{
sort: {_id: -1},
upsert: true
})
.then(result => {
console.log('Subtracted One Like')
response.json('Like Subtracted')
})
.catch(error => console.error(error))
})
app.delete('/deleteQuote', (request, response) => {
db.collection('motivational-quotes').deleteOne({quoteName: request.body.quoteNameS})
.then(result => {
console.log('Quote Deleted')
response.json('Quote Deleted')
})
.catch(error => console.error(error))
})
app.listen(PORT, ()=>{
console.log(`Server running on port ${PORT}`)
})