-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
95 lines (83 loc) · 2.03 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
93
94
95
var express = require("express"),
app = express(),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
expressSanitizer = require("express-sanitizer"),
methodOverride = require('method-override');
mongoose.connect("mongodb://localhost/stokcsi");
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressSanitizer());
app.set("view engine", "ejs");
app.use(methodOverride('_method'));
var stockSchema = new mongoose.Schema({
text: String,
});
var Stock = mongoose.model("Stock", stockSchema);
app.get("/", function(req, res){
res.redirect("/stocks");
});
app.get("/", function(req, res){
Stock.find({}, function(err, stocks){
if(err){
console.log(err);
} else {
res.render("index", {stocks: stocks});
}
})
});
app.get("/stocks", function(req, res){
Stock.find({}, function(err, stocks){
if(err){
console.log(err);
} else {
res.render("index", {stocks: stocks});
}
})
});
app.get("/stocks/new", function(req, res){
res.render("new");
});
app.post("/stocks", function(req, res){
req.body.stock.text = req.sanitize(req.body.stock.text);
var formData = req.body.stock;
Stock.create(formData, function(err, newStock){
if(err){
res.render("new");
} else {
res.redirect("/stocks");
}
});
});
app.get("/stocks/:id/edit", function(req, res){
Stock.findById(req.params.id, function(err, stock){
if(err){
console.log(err);
res.redirect("/")
} else {
res.render("edit", {stock: stock});
}
});
});
app.put("/stocks/:id", function(req, res){
Stock.findByIdAndUpdate(req.params.id, req.body.stock, function(err, stock){
if(err){
console.log(err);
} else {
res.redirect('/');
}
});
});
app.delete("/stocks/:id", function(req, res){
Stock.findById(req.params.id, function(err, stock){
if(err){
console.log(err);
} else {
stock.remove();
res.redirect("/stocks");
}
});
});
app.listen(5000, function() {
console.log('Server running on port 5000');
});