forked from seeschweiler/mern-stack-part-02
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
72 lines (61 loc) · 2.04 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
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const listingRoutes = express.Router();
const PORT = 4000;
let Listing = require('./listing.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/listings', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established successfully");
})
listingRoutes.route('/').get(function(req, res) {
Listing.find(function(err, listings) {
if (err) {
console.log(err);
} else {
res.json(listing);
}
});
});
listingRoutes.route('/:id').get(function(req, res) {
let id = req.params.id;
Listing.findById(id, function(err, listing) {
res.json(listing);
});
});
listingRoutes.route('/add').post(function(req, res) {
let listing = new listing(req.body);
listing.save()
.then(listing => {
res.status(200).json({'listing': 'listing added successfully'});
})
.catch(err => {
res.status(400).send('adding new listing failed');
});
});
listingRoutes.route('/update/:id').post(function(req, res) {
listing.findById(req.params.id, function(err, listing) {
if (!listing)
res.status(404).send('data is not found');
else
listing.listing_description = req.body.lisiting_description;
listing.listing_location = req.body.listing_location;
listing.listing_link = req.body.listing_link;
listing.listing_name = req.body.listing_name;
listing.save().then(listing => {
res.json('Listing updated');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
app.use('/Listings', todoRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});