-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
92 lines (89 loc) · 2.16 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
const methodOverride = require("method-override");
mongoose.connect("mongodb://localhost/blog_app", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride("_method"));
// Schema
const blogSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
body: {
type: String,
required: true,
},
created: { type: Date, default: Date.now },
});
const Blog = mongoose.model("blog", blogSchema);
// Routes
app.get("/", (req, res) => {
res.redirect("/blogs");
});
// Index Routes
app.get("/blogs", async (req, res) => {
try {
const blogs = await Blog.find();
res.render("index", { blogs: blogs });
} catch (error) {
console.error("routing in Blogs", error);
}
});
// New Form
app.get("/blogs/new", (req, res) => {
res.render("new");
});
// Create
app.post("/blogs", async (req, res) => {
try {
await Blog.create(req.body.blog);
res.redirect("/blogs");
} catch (error) {
console.error("Create new blog", error);
}
});
// Show Route
app.get("/blogs/:id", async (req, res) => {
try {
const blog = await Blog.findById(req.params.id);
res.render("blogPage", { blog: blog });
} catch (error) {
res.redirect("/blogs");
console.log("BlogPage Error", error);
}
});
// edit
app.get("/blogs/:id/edit", async (req, res) => {
const blog = await Blog.findById(req.params.id);
res.render("edit", { blog: blog });
});
app.put("/blogs/:id", async (req, res) => {
try {
await Blog.findByIdAndUpdate(req.params.id, req.body.blog);
res.redirect("/blogs/" + req.params.id);
} catch (error) {
res.redirect("/blogs");
console.log("Editing Error", error);
}
});
// delete
app.delete("/blogs/:id", async (req, res) => {
await Blog.findByIdAndRemove(req.params.id);
res.redirect("/blogs");
});
const port = 5000;
app.listen(5000, function () {
console.log(`http://localhost:${port}`);
});