-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
62 lines (48 loc) · 1.81 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
const express = require("express");
const parser = require("body-parser");
const mongoClient = require("mongodb").MongoClient;
const fs = require("fs");
const app = express();
let database = {};
database.connectionString =
"mongodb+srv://DepthDweller21:[email protected]/";
const PORT = 5000;
// not sure what this is but I need it to do something related to json, parsing, urls and APIs, will find out soon enough
app.use(parser.urlencoded({ extended: true }));
// renders everything in the public folder
app.use(express.static("public"));
//connecting to database
async function runDatabase() {
console.log(`running database`);
try {
const client = await mongoClient.connect(database.connectionString);
console.log("Connected to Database Mr.Duck");
database.quotesCollection = client.db("crud-app").collection("quotes");
} catch (err) {
console.log(err);
}
}
/* all this till now was the application initialisation
this line of code listens on path /quotes which the HTML responds on*/
app.post("/addQuotes", async (req, res) => {
try {
await database.quotesCollection.insertOne(req.body);
res.redirect("/");
} catch (err) {
console.error(err);
}
});
app.get("/getQuotes", async (req, res) => {
let search = req.query.searchName.toLowerCase();
let quotesCollection = await database.quotesCollection.find().toArray();
let searchResult = quotesCollection.filter((element) =>element.name == search ? true : false);
res.json(searchResult);
});
//P0YvljIktS2BbbVN
// this line of code uses express to launch the site on localhost PORT as shown in the variable section
runDatabase().then(()=>{
app.listen(process.env.PORT ||PORT, function () {
console.log(
`server is live Mr.Duck on port: ${PORT}, please visit the project on localhost:${PORT}`
);
})});