-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
96 lines (87 loc) · 2.03 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
//npm install express mongoose ejs dotenv
//npm install --save-dev nodemon
//declare variables
const express = require("express");
const app = express();
const PORT = process.env.PORT || 8500;
const mongoose = require("mongoose");
// const { restart } = require("nodemon");
const TodoTask = require("./models/todotask");
require("dotenv").config();
//set middleware
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
(err) => {
if (err) {
console.log(err);
} else {
console.log("Connected to DB");
}
}
);
// GET METHOD
app.get("/", async (req, res) => {
try {
TodoTask.find({}, (err, tasks) => {
res.render("index.ejs", { todotasks: tasks });
});
} catch (err) {
if (err) return res.status(500).send(err);
}
});
//POST METHOD
app.post("/", async (req, res) => {
const todoTask = new TodoTask({
title: req.body.title,
content: req.body.content,
});
try {
await todoTask.save();
console.log(todoTask);
res.redirect("/");
} catch (err) {
if (err) return res.status(500).send(err);
res.redirect("/");
}
});
//EDIT or UPDATE METHOD
app
.route("/edit/:id")
.get((req, res) => {
const id = req.params.id;
TodoTask.find({}, (err, tasks) => {
res.render("edit.ejs", {
todoTasks: tasks,
idTask: id,
});
});
})
.post((req, res) => {
const id = req.params.id;
TodoTask.findByIdAndUpdate(
id,
{
title: req.body.title,
content: req.body.content,
},
(err) => {
if (err) return res.status(500).send(err);
res.redirect("/");
}
);
});
//delete
app
.route("/remove/:id")
.get((req, res) => {
const id = req.params.id;
TodoTask.findByIdAndRemove(id, (err) => {
if (err) return res.status(500).send(err);
res.redirect("/");
});
});
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));