-
Notifications
You must be signed in to change notification settings - Fork 1
/
people.js
106 lines (84 loc) · 1.97 KB
/
people.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
96
97
98
99
100
101
102
103
104
105
106
var express = require('express'),
router = express.Router(),
mongoose = require('mongoose'),
Person = mongoose.model('Person');
module.exports = function (app) {
app.use('/api/people', router);
};
/**
* @api {post} /people Create a person
* @apiName CreatePerson
* @apiGroup People
*
* @apiSuccess {String} age Age of the person.
*/
router.post('/', function (req, res, next) {
var person = new Person(req.body);
person.save(function (err, createdPerson) {
if (err) {
res.status(500).send(err);
return;
}
res.send(createdPerson);
});
});
// GET /api/people
router.get('/', function (req, res, next) {
Person.find(function (err, people) {
if (err) {
res.status(500).send(err);
return;
}
res.send(people);
});
});
// GET /api/people/:id
router.get('/:id', function (req, res, next) {
var personId = req.params.id;
Person.findById(personId, function(err, person) {
if (err) {
res.status(500).send(err);
return;
} else if (!person) {
res.status(404).send('Person not found');
return;
}
res.send(person);
});
});
// PUT /api/people/:id
router.put('/:id', function (req, res, next) {
var personId = req.params.id;
Person.findById(personId, function(err, person) {
if (err) {
res.status(500).send(err);
return;
} else if (!person) {
res.status(404).send('Person not found');
return;
}
person.name = req.body.name;
person.age = req.body.age;
person.save(function(err, updatedPerson) {
if (err) {
res.status(500).send(err);
return;
}
res.send(updatedPerson);
});
});
});
// DELETE /api/people/:id
router.delete('/:id', function (req, res, next) {
var personId = req.params.id;
Person.remove({
_id: personId
}, function(err, data) {
if (err) {
res.status(500).send(err);
return;
}
console.log('Deleted ' + data + ' documents');
res.sendStatus(204);
});
});