forked from meghannfh/GomiAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
97 lines (86 loc) · 2.31 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
90
91
92
93
94
95
96
const express = require("express");
const app = express();
const { MongoClient, ObjectId } = require("mongodb");
const cors = require("cors");
const { response } = require("express");
require('dotenv').config({ path: './config/.env' })
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
let db;
// let dbName = "garbage-disposal-api"
let dbName = "nagaiGomi2"
let dbConnectionStr = process.env.DB_STRING2
MongoClient.connect(dbConnectionStr)
.then(
(client) => {
console.log(`Connected to ${dbName} Database`);
db = client.db("nagaiGomi2");
}
);
app.get("/", (req, res) => {
res.render("index.ejs")
});
app.get("/search", async (request, response) => {
try {
// console.log(req.query);
let result = await db.collection("nagai-gomi").aggregate([
{
"$search": {
"autocomplete": {
"query": `${request.query.query}`,
"path": "name",
"fuzzy": {
"maxEdits": 1,
"prefixLength": 2,
"maxExpansions": 5
},
"score": {
"boost": {
"value": 3
}
}
}
}
},
{
"$limit": 7
}
]).toArray();
response.send(result);
} catch (error) {
response.status(500).send({ message: error.message });
console.log(error)
}
});
app.get("/get/:id", async (request, response) => {
try {
console.log(request.params);
let result = await db.collection("nagai-gomi").findOne({
"_id": ObjectId(request.params.id)
});
console.log(result);
response.send(result);
} catch (error) {
response.status(500).send({ message: error.message });
}
});
//link to form in ejs
app.post('/add', async (request, response) => {
try{
let newItem = await db.collection('nagai-gomi').insertOne({
name: request.body.name,
material: request.body.material,
classification: request.body.classification,
instructions: request.body.instructions,
contact: request.body.contact
})
response.redirect('/')
}catch (error){
}
})
app.listen(process.env.PORT || PORT, () => {
console.log("Server is running.");
});