-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (60 loc) · 1.56 KB
/
index.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
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
//models
const TodoTask = require("./models/TodoTask");
dotenv.config();
app.use("/static", express.static("public"));
//extract data from form and add to res body
app.use(express.urlencoded({ extended: true }));
//connection to db
mongoose.connect(process.env.DB_CONNECT, () => {
console.log("Connected to db!");
app.listen(3000, () => console.log("Server Up and running"));
});
//View Engine Configuration
app.set("view engine", "ejs");
//GET Method
app.get("/", (req, res) => {
TodoTask.find({}, (err, tasks) => {
res.render("todo.ejs", { todoTasks: tasks });
});
});
//POST Method
app.post("/", async (req, res) => {
const todoTask = new TodoTask({
content: req.body.content,
});
try {
await todoTask.save();
res.redirect("/");
} catch (err) {
console.log(err);
res.redirect("/");
}
});
//UPDATE Method
app
.route("/edit/:id")
.get((req, res) => {
const id = req.params.id;
TodoTask.find({}, (err, tasks) => {
res.render("todoEdit.ejs", { todoTasks: tasks, idTask: id });
});
})
.post((req, res) => {
const id = req.params.id;
TodoTask.findByIdAndUpdate(id, { content: req.body.content }, (err) => {
if (err) return res.send(500, err);
res.redirect("/");
});
});
//DELETE
app.route("/remove/:id").get((req, res) => {
const id = req.params.id;
TodoTask.findByIdAndRemove(id, (err) => {
if (err) return res.send(500, err);
res.redirect("/");
});
});