-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
68 lines (57 loc) · 1.86 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
console.log('May node be with ou!');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
var db;
MongoClient.connect('mongodb://Mytestuser:mytestuserpass@ds231245.mlab.com:31245/some-favorite-famous-quotes', (err, database) => {
if (err) return console.log(err);
db = database;
//start the server
app.listen(3000, ()=> {
console.log('listening on 3000');
})
})
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.static('public'))
app.get('/', (req, res) => {
//res.send('Hello World$$$')
//Note: __dirname is directory that contains the JavaScript source code. Try logging it and see what you get!
//res.sendFile(__dirname + '/index.html')
var cursor = db.collection('quotes').find().toArray((err, result)=>{
if (err) return console.log(err)
res.render('index.ejs', {quotes: result})
})
//console.log(cursor)
})
app.post('/quotes', (req, res) => {
//console.log(req.body)
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: 'Yoda'},
{$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.send({message: 'A quote was deleted'})
})
})