-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
76 lines (56 loc) · 1.6 KB
/
Copy pathserver.js
File metadata and controls
76 lines (56 loc) · 1.6 KB
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
const express = require("express");
const app = express();
const mongoose = require('mongoose');
const HTTP_PORT = process.env.PORT || 8080;
const DB = `Full MongoDB Connection String Here`;
app.set("view engine", "ejs");
let Schema = mongoose.Schema;
const nameSchema = new Schema({
fName: String,
lName: String
});
let Name = mongoose.model('names', nameSchema);
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.get("/", (req, res) => {
Name.find().sort({createdAt: 1}).exec().then((data) => {
res.render("home", { data });
}).catch(err=>{
console.log(err);
});
});
app.post("/updateName", (req, res) => {
if (req.body.lName.length == 0 && req.body.fName.length == 0) {
Name.deleteOne({_id: req.body._id}).exec().then(() => {
console.log("successfully removed name: " + req.body._id);
res.redirect("/");
});
} else {
Name.updateOne({_id: req.body._id}, {
$set: {
lName: req.body.lName,
fName: req.body.fName
}
}).exec().then(() => {
console.log("successfully updated name: " + req.body._id);
res.redirect("/");
});
}
});
app.post("/addName", (req, res) => {
const newName = new Name({
lName: req.body.lName,
fName: req.body.fName
});
newName.save().then(() => {
console.log("successfully created a new name");
res.redirect("/");
});
});
mongoose.connect(DB).then(()=>{
app.listen(HTTP_PORT, ()=>{
console.log(`server listening on: ${HTTP_PORT}`);
});
}).catch(err=>{
console.log(err);
})