forked from Montana-Code-School/expressMongooseReview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
73 lines (67 loc) · 1.84 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
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Chair = require('./models/chair.js');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/chairs');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function () { console.log("chairs db has connected") });
app.use(express.static('public'));
app.use(bodyParser.json({ type: 'application/json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/chairs", function (req, res, next) {
Chair.find(function (err, chairs) {
if (err) {
console.log(err);
next(err);
} else {
res.json(chairs);
}
});
});
app.post("/chairs", function (req, res, next) {
var chair = new Chair();
chair.type = req.body.type;
chair.model = req.body.model;
chair.save(function (err, chairReturned) {
if (err) {
console.log(err);
console.log(req.body);
next(err);
} else {
res.json("chair put in database" + chairReturned.model);
}
});
});
app.delete("/chairs", function (req, res, next) {
Chair.findByIdAndRemove(req.body.id, function (err, chair) {
if (err) {
console.log(err);
next(err);
} else {
res.json('succesfully deleted' + chair);
}
});
});
app.put("/chairs", function (req, res, next) {
Chair.findById(req.body.id, function (err, chair) {
if (err) {
console.log(err);
} else {
chair.type = req.body.type;
chair.model = req.body.model;
chair.save(function (err, chairReturned) {
if (err) {
console.log(err);
console.log(req.body);
} else {
res.json("chair put in database" + chairReturned.model);
}
});
}
});
});
app.listen(5000, function () {
console.log("Listening at: 5000");
});