-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
85 lines (75 loc) · 2.06 KB
/
server.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
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
var promise = mongoose.connect('mongodb://haseeb:haseeb@ds161042.mlab.com:61042/mycontacts', {useMongoClient: true});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.static('dist'));
var contactSchema = new mongoose.Schema({
name: String,
email: String,
phone: Number,
picture: String
});
var Contact = mongoose.model('Contact', contactSchema);
app.get('/contacts', function(req, res){
Contact.find({}, function(err, contacts){
if(err){
res.send(err);
} else {
res.json(contacts);
}
});
});
app.get('/contacts/:id', function(req, res){
Contact.findById(req.params.id, function(err, foundContact){
if(err){
res.send(err);
} else {
res.json(foundContact);
}
});
});
app.post('/contacts', function(req, res){
var newContact = new Contact();
newContact.name = req.body.name;
newContact.email = req.body.email;
newContact.phone = req.body.phone;
newContact.picture = req.body.picture;
newContact.save(function(err, savedContact){
if(err){
res.send(err);
} else {
res.json(savedContact);
}
});
});
app.put('/contacts/:id', function(req, res){
Contact.findByIdAndUpdate(req.params.id,
{
$set: {name: req.body.name, email: req.body.email, phone: req.body.phone, picture: req.body.picture}
},
{
new: true
},
function(err, updatedContact){
if(err){
res.send(err);
} else {
res.json(updatedContact);
}
});
});
app.delete('/contacts/:id', function(req, res){
Contact.findByIdAndRemove(req.params.id, function(err, deletedContact){
if(err){
res.send(err);
} else {
res.json(deletedContact);
}
});
});
app.listen(3000, function(){
console.log('Server started on port 3000');
});