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