-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
79 lines (66 loc) · 2.27 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
const mongoose = require("mongoose");
const express = require("express");
const path = require("path");
const Listing = require("./models/listing");
const methodOverride = require("method-override");
const ejsMate = require("ejs-mate");
const app = express();
const port = 8080;
const MONGO_URI = "mongodb://127.0.0.1:27017/wanderspot";
main()
.then(() => "Connection Successful")
.catch((err) => console.log(err));
async function main() {
await mongoose.connect(MONGO_URI);
}
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride("_method"));
app.engine("ejs", ejsMate);
// Home route
app.get("/", (req, res) => {
res.send("Connected to the server");
});
// Show all listings route
app.get("/listings", async (req, res) => {
const listings = await Listing.find({});
res.render("listings/index", { listings });
});
// Create new listing route (GET request to show the form)
app.get("/listings/new", (req, res) => {
res.render("listings/new");
});
// Create new listing route (POST request to create the listing)
app.post("/listings", async (req, res) => {
const newListing = new Listing(req.body.listing);
await newListing.save();
res.redirect("/listings");
});
// Show individual listing route
app.get("/listings/:id", async (req, res) => {
let { id } = req.params;
let listing = await Listing.findById(id);
res.render("listings/show", { listing });
});
// Edit listing route (GET request to show the form)
app.get("/listings/:id/edit", async (req, res) => {
let { id } = req.params;
let listing = await Listing.findById(id);
res.render("listings/edit", { listing });
});
// Edit listing route (PUT request to update the listing)
app.put("/listings/:id", async (req, res) => {
let { id } = req.params;
let listing = await Listing.findByIdAndUpdate(id, { ...req.body.listing });
res.redirect(`/listings/${listing._id}`);
});
// Delete listing route
app.delete("/listings/:id", async (req, res) => {
let { id } = req.params;
let deletedListing = await Listing.findByIdAndDelete(id);
console.log(deletedListing);
res.redirect("/listings");
});
app.listen(port, () => console.log("Listening on port " + port));