-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
75 lines (64 loc) · 1.65 KB
/
server.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
require("dotenv").config();
const express = require("express");
const app = express();
// const fruits = require("./models/fruits");
const Fruit = require("./models/fruits");
const mongoose = require("mongoose");
app.set("view engine", "jsx");
app.engine("jsx", require("express-react-views").createEngine());
// ===== Connection to Database ===== //
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.once("open", () => {
console.log("connected to mongo");
});
// ===== Middleware ===== //
app.use((req, res, next) => {
console.log("I run for all routes");
next();
});
app.use(express.urlencoded({ extended: false }));
// ===== Routes ===== //
// I.N.D.U.C.E.S
// Index, New, Delete, Update, Create, Edit, Show
// Index
app.get("/fruits", (req, res) => {
Fruit.find({}, (error, allFruits) => {
res.render("Index", {
fruits: allFruits,
});
});
});
// New
app.get("/fruits/new", (req, res) => {
res.render("New");
});
// Delete
// Update
// Create
app.post("/fruits", (req, res) => {
if (req.body.readyToEat === "on") {
//if checked, req.body.readyToEat is set to 'on'
req.body.readyToEat = true; //do some data correction
} else {
//if not checked, req.body.readyToEat is undefined
req.body.readyToEat = false; //do some data correction
}
Fruit.create(req.body, (error, createdFruit) => {
res.redirect('/fruits');
});
});
// Edit
// Show
app.get("/fruits/:id", (req, res) => {
Fruit.findById(req.params.id, (err, foundFruit) => {
res.render('Show', {
fruit: foundFruit
});
});
});
app.listen(3000, () => {
console.log("listening");
});