-
Notifications
You must be signed in to change notification settings - Fork 0
/
PetController.js
59 lines (53 loc) · 1.89 KB
/
PetController.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
// PetController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
var Pet = require('./Pet');
// CREATES A NEW PET
router.post('/', function (req, res) {
Pet.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
phone: req.body.phone,
state: req.body.state,
city: req.body.city,
address: req.body.address
},
function (err, pet) {
if (err) return res.status(500).send("There was a problem adding the information to the database.");
res.status(200).send(pet);
console.log(pet)
});
});
// RETURNS ALL THE PETS IN THE DATABASE
router.get('/', function (req, res) {
Pet.find({}, function (err, pets) {
if (err) return res.status(500).send("There was a problem finding the pets.");
res.status(200).send(pets);
});
});
// GETS A SINGLE PET FROM THE DATABASE
router.get('/:id', function (req, res) {
Pet.findById(req.params.id, function (err, pet) {
if (err) return res.status(500).send("There was a problem finding the pet.");
if (!pet) return res.status(404).send("No pet found.");
res.status(200).send(pet);
});
});
// DELETES A PET FROM THE DATABASE
router.delete('/:id', function (req, res) {
Pet.findByIdAndRemove(req.params.id, function (err, pet) {
if (err) return res.status(500).send("There was a problem deleting the pet.");
res.status(200).send("Pet "+ pet.name +" was deleted.");
});
});
// UPDATES A SINGLE PET IN THE DATABASE
router.put('/:id', function (req, res) {
Pet.findByIdAndUpdate(req.params.id, req.body, {new: true}, function (err, pet) {
if (err) return res.status(500).send("There was a problem updating the pet.");
res.status(200).send(pet);
});
});
module.exports = router;