-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (65 loc) · 1.66 KB
/
index.js
File metadata and controls
76 lines (65 loc) · 1.66 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
75
76
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const Notes = require("./models/notes.model");
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static("public"));
// Routes
app.get("/", async (req, res) => {
try {
const notes = await Notes.find();
res.render("home", { notes });
} catch (err) {
res.status(500).send("Database error");
}
});
app.get("/new", (req, res) => {
res.render("new");
});
app.get("/view/:id", async (req, res) => {
try {
const note = await Notes.findById(req.params.id);
res.render("show", { note });
} catch (err) {
res.redirect("/");
}
});
app.post("/new", async (req, res) => {
await Notes.create(req.body);
res.redirect("/");
});
app.get("/edit/:id", async (req, res) => {
try {
const note = await Notes.findById(req.params.id);
res.render("edit", { note });
} catch (err) {
res.redirect("/");
}
});
app.post("/edit/:id", async (req, res) => {
await Notes.findByIdAndUpdate(req.params.id, req.body);
res.redirect("/");
});
app.post("/delete/:id", async (req, res) => {
await Notes.findByIdAndDelete(req.params.id);
res.redirect("/");
});
// Connect then start server
async function connectDB() {
try {
await mongoose.connect(process.env.MONGO_URL);
console.log("MongoDB Connected");
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
} catch (err) {
console.log("DB Error:", err);
process.exit(1);
}
}
connectDB();