-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
52 lines (44 loc) · 1.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
const dotenv = require('dotenv');
dotenv.config();
const name = process.env.NAME || 'User'
console.log('http://localhost:3000')
const express = require('express');
const bodyParser = require('body-parser')
const app = express();
app.set('view engine', 'ejs')
app.use(express.static('public'))
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect(process.env.URL, { useUnifiedTopology: true })
.then(client => {
console.log('Connected to database')
const db = client.db('books')
const titlesCollection = db.collection('titles')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
db.collection('titles').find().toArray()
.then(results => {
res.render('index.ejs', { titles: results, name: name })
})
.catch(error => console.error(error))
})
app.post('/titles', (req, res) => {
titlesCollection.insertOne(req.body)
.then(result => {
res.redirect('/')
})
.catch(error => console.error(error))
console.log(req.body)
})
app.listen(3000, function() {
console.log('listening on 3000')
})
app.delete('/titles', (req, res) => {
titlesCollection.deleteOne({})
.then(result => {
res.json('Delete one title')
})
.catch(error => console.error(error))
})
})
.catch(error => console.error(error))