-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser-controller.js
110 lines (99 loc) · 3.09 KB
/
user-controller.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
107
108
109
110
const { User } = require('../models');
const userController = {
// get all users
getAllUser(req, res) {
User.find({})
.select('-__v')
.then(dbUserData => res.json(dbUserData))
.catch(err => {
console.log(err);
res.status(400).json(err);
});
},
// get one User by id
getUserById({ params }, res) {
User.findOne({ _id: params.id })
.populate({
path: 'thoughts',
select: '-__v'
})
.populate({
path: 'friends',
select: '-__v'
})
.select('-__v')
.then(dbUserData => {
// If no User is found, send 404
if (!dbUserData) {
res.status(404).json({ message: 'No User found with this id!' });
return;
}
res.json(dbUserData);
})
.catch(err => {
console.log(err);
res.status(400).json(err);
});
},
// createUser
createUser({ body }, res) {
User.create(body)
.then(dbUserData => res.json(dbUserData))
.catch(err => res.status(400).json(err));
},
// update User by id
updateUser({ params, body }, res) {
User.findOneAndUpdate({ _id: params.id }, body, { new: true, runValidators: true })
.then(dbUserData => {
if (!dbUserData) {
res.status(404).json({ message: 'No User found with this id!' });
return;
}
res.json(dbUserData);
})
.catch(err => res.status(400).json(err));
},
// delete User
deleteUser({ params }, res) {
User.findOneAndDelete({ _id: params.id })
.then(dbUserData => {
if (!dbUserData) {
res.status(404).json({ message: 'No User found with this id!' });
return;
}
res.json(dbUserData);
})
.catch(err => res.status(400).json(err));
},
addFriend({ params }, res) {
User.findOneAndUpdate(
{_id: params.userId},
{ $push: { friends: params.friendId} },
{ new: true, runValidators: true}
)
.then(dbUserData => {
if (!dbUserData) {
res.status(404).json({ message: 'No user found with this id!'});
return;
}
res.json(dbUserData);
})
.catch(err => res.json(err));
},
deleteFriend({ params }, res) {
User.findOneAndUpdate(
{_id: params.userId},
{ $pull: { friends: params.friendId} },
{ new: true, runValidators: true}
)
.then(dbUserData => {
if (!dbUserData) {
res.status(404).json({ message: 'No user found with this id!'});
return;
}
res.json(dbUserData);
})
.catch(err => res.json(err));
}
}
module.exports = userController;