-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
73 lines (61 loc) · 1.64 KB
/
app.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
// Imports
const express = require("express")
const bodyParser = require("body-parser");
const mongoose = require("mongoose")
const date = require(__dirname + "/date")
require("dotenv").config()
// Constants
const app = express()
const port = process.env.PORT || 3000;
const today = date.getDay();
const mongo_url = process.env.MONGO_URL
let error = false
const errorMessage = "Please Enter a valid name for To-Do."
// App Methods
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(__dirname + "/public"))
app.set("view engine", "ejs")
// Database
mongoose.connect(mongo_url, { useNewUrlParser: true }, (err) => {
if (err) throw err;
console.log("DB Connected successfully");
});
const itemSchema = {
name: String
}
const Item = mongoose.model("Item", itemSchema);
// Routes
app.get("/", (req, res) => {
Item.find({}, (err, items) => {
if (err) throw (err)
res.render("list", { listTitle: today, todos: items, error, errorMessage });
})
})
app.post("/", (req, res) => {
const todo = (req.body.todo).trim();
if (todo == "") {
error = true;
}
else {
const item = new Item({
name: todo
})
item.save();
}
res.redirect("/")
})
app.post("/delete", (req, res) => {
const todo_id = req.body.deleteTodo;
Item.findByIdAndRemove(todo_id, (err) => {
if(err) throw (err)
console.log("Successfully Deleted todo with id " + todo_id)
})
res.redirect("/")
})
app.post("/error", (req, res) => {
error = false;
res.redirect("/")
})
app.listen(port, () => {
console.log(`Server is Running on Port ${port}`)
})