Datasets:
Add code/1749192826066_userController.js
Browse files
code/1749192826066_userController.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const User = require('./User'); // Thay './User' bằng đường dẫn thực tế đến file mô hình User của bạn
|
| 2 |
+
|
| 3 |
+
// Lấy tất cả người dùng
|
| 4 |
+
exports.getAllUsers = async (req, res) => {
|
| 5 |
+
try {
|
| 6 |
+
const users = await User.find();
|
| 7 |
+
res.status(200).json(users);
|
| 8 |
+
} catch (err) {
|
| 9 |
+
res.status(500).send(err);
|
| 10 |
+
}
|
| 11 |
+
};
|
| 12 |
+
|
| 13 |
+
// Lấy người dùng theo ID
|
| 14 |
+
exports.getUserById = async (req, res) => {
|
| 15 |
+
try {
|
| 16 |
+
const user = await User.findById(req.params.id);
|
| 17 |
+
res.status(200).json(user);
|
| 18 |
+
} catch (err) {
|
| 19 |
+
res.status(500).send(err);
|
| 20 |
+
}
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
// Tạo một người dùng mới
|
| 24 |
+
exports.createUser = async (req, res) => {
|
| 25 |
+
try {
|
| 26 |
+
const newUser = new User(req.body);
|
| 27 |
+
await newUser.save();
|
| 28 |
+
res.status(201).send(newUser);
|
| 29 |
+
} catch (err) {
|
| 30 |
+
res.status(500).send(err);
|
| 31 |
+
}
|
| 32 |
+
};
|
| 33 |
+
|
| 34 |
+
// Cập nhật một người dùng
|
| 35 |
+
exports.updateUser = async (req, res) => {
|
| 36 |
+
try {
|
| 37 |
+
const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
|
| 38 |
+
res.status(200).json(updatedUser);
|
| 39 |
+
} catch (err) {
|
| 40 |
+
res.status(500).send(err);
|
| 41 |
+
}
|
| 42 |
+
};
|
| 43 |
+
|
| 44 |
+
// Xóa một người dùng
|
| 45 |
+
exports.deleteUser = async (req, res) => {
|
| 46 |
+
try {
|
| 47 |
+
await User.findByIdAndDelete(req.params.id);
|
| 48 |
+
res.status(204).send();
|
| 49 |
+
} catch (err) {
|
| 50 |
+
res.status(500).send(err);
|
| 51 |
+
}
|
| 52 |
+
};
|