-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
58 lines (48 loc) · 1.48 KB
/
index.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
const express = require('express')
const mongoose = require('mongoose')
const UserModel = require('./User')
var cors = require('cors')
const app = express()
const port = 3001
app.use(cors())
app.use(express.json())
mongoose.connect('mongodb://127.0.0.1/GaborniLE1', {
useNewUrlParser: true, //optional to avoid display warning
useUnifiedTopology: true //optional to avoid display warning
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
app.get('/', (req, res) => {
UserModel.find()
.then(users => res.json(users))
.catch(err => res.json(err))
})
app.get('/get/:id', (req, res) => {
const id = req.params.id
UserModel.findById({ _id: id })
.then(post => res.json(post))
.catch(err => console.log(err))
})
app.post('/create', (req, res) => {
UserModel.create(req.body)
.then(user => res.json(user))
.catch(err => res.json(err))
})
app.put('/update/:id', (req, res) => {
const id = req.params.id;
UserModel.findByIdAndUpdate({ _id: id }, {
name: req.body.name,
email: req.body.email,
age: req.body.age
}).then(user => res.json(user))
.catch(err => res.json(err))
})
app.delete('/deleteuser/:id', (req, res) => {
const id = req.params.id;
UserModel.findByIdAndDelete({ _id: id })
.then(response => res.json(response))
.catch(err => res.json(err))
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})