-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
89 lines (76 loc) · 2.01 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
/*jshint esversion: 6, node: true */
"use strict";
const express = require("express");
const bodyParser = require("body-parser");
const MongoClient = require("mongodb").MongoClient;
const app = express();
var db;
const mongoURL = "mongodb://kanthalion:[email protected]:19210/star-wars-quotes";
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static("public"));
app.set("view engine", "ejs");
MongoClient.connect(mongoURL, (err, database) => {
if (err) return console.error(err);
db = database;
app.listen(process.env.PORT || 3000, function() {
console.log("listening on " + (process.env.PORT || 3000));
});
});
app.get("/", (req, res) => {
db.collection("quotes").find().toArray((err, results) => {
if (err) return console.error(err);
res.render("index.ejs", {
quotes: results
});
console.log(results);
});
});
app.post("/quotes", (req, res) => {
db.collection("quotes").save(req.body, (err, result) => {
if (err) return console.error(err);
console.log("saved to database");
res.redirect("/");
});
});
app.put("/quotes", (req, res) => {
// Handle put request
db.collection("quotes").findOneAndUpdate(
// query
{
name: "Yoda"
},
// update
{
$set: {
name: req.body.name,
quote: req.body.quote
}
},
// options
{
sort: {
_id: -1
},
upsert: true
},
// callback
(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");
}
);
});