-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (63 loc) · 1.73 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const express = require('express');
const mongoose = require('mongoose');
// mongodb setup
const dbURI = process.env.DB_URL;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => console.log('connected to db'))
.catch(err => console.log(err));
const app= express();
app.use(express.json())
// User Schema
const Schema = mongoose.Schema;
const UserSchema = new Schema({
email: {
type: String,
required: true,
},
Name: {
type: String,
required: true,
},
bio : {
type: String
}
}, { timestamps: true });
const User = mongoose.model('User', UserSchema);
module.exports = User;
app.get('/user', (req,res)=>{
user.find()
.then(data => res.send(data))
.catch(err => res.status(400).send(err))
})
app.post('/user', (req,res)=>{
const user = new User({
name: req.body.name,
email: req.body.email,
bio: req.body.bio
})
user.save()
.then(data => res.send('User saved'))
.catch(err => res.status(400).send(err))
})
app.get('/user/:id', (req,res)=>{
user.findOne({_id : req.params.id})
.then(data => res.send(data))
.catch(err => res.status(400).send(err))
})
app.put('/user/:id', (req,res)=>{
const user = new User({
name: req.body.name,
email: req.body.email,
bio: req.body.bio
})
user.save()
.then(data => res.send('User updated'))
.catch(err => res.status(400).send(err))
})
app.get('/user/:id', (req,res)=>{
user.findOneAndDelete({_id : req.params.id})
.then(data => res.send('User deleted'))
.catch(err => res.status(400).send(err))
})
const port = process.env.PORT || 5000
app.listen(port, console.log(`app is running on port ${port}, go to http://localhost:${port}`))