-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10_express_mongoose.js
83 lines (59 loc) · 1.76 KB
/
10_express_mongoose.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
const User2 = require('./10_mongoose_model')
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
app.use(express.json())
app.post('/users', (req, res) => {
const user = new User2(req.body)
user.save().then(() => {
res.send(user) //or res.status(201).send(user) --> post sends 201 if successful
}).catch((e) => {
res.status(400).send(e)
})
})
app.listen(port, () => {
console.log('Server is up on port ' + port)
})
app.get('/users', (req, res) => {
User2.find({}).then((users) => {
res.send(users)
}).catch((e) => {
res.status(500).send()
})
})
app.get('/users/:id', async (req, res) => {
const _id = req.params.id
const user = await User2.findById(_id);
if (!user) {
return res.status(404).send()
}
res.status(202).send(user)
})
app.patch('/users/:id', async (req, res) => {
const updates = Object.keys(req.body)
const allowedUpdates = ['name', 'email', 'password', 'age']
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send({ error: 'Invalid updates!' })
}
try {
const user = await User2.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true })
if (!user) {
return res.status(404).send()
}
res.send(user)
} catch (e) {
res.status(400).send(e)
}
})
app.delete('/users/:id', async (req, res) => {
try {
const user = await User2.findByIdAndDelete(req.params.id)
if (!user) {
return res.status(404).send()
}
res.send(user)
} catch (e) {
res.status(500).send()
}
})