-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (45 loc) · 1.55 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
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const keys = require('./config/keys');
require('./models/Car');
// Create app level object of Express JS
const app = express();
// Parse incoming request bodies in a middleware
// Available req.body
app.use(bodyParser.urlencoded({ extended: true}));
// [ PUBLIC ] - For static assets
app.use(express.static(__dirname + "/public"));
/***********************************/
/* [ Controllers ] */
/***********************************/
// [GET - Request cars]
app.get('/cars', (req, res, next) => {
const resultArray = [];
mongoose.connect(keys.mongoURI, function(err, db) {
const cursor = db.collection('fancycars').find();
// [ ITERATE ] - push data to results.
cursor.forEach((data, err) => {
resultArray.push(data);
}, function() {
db.close();
res.status(200).send(resultArray);
}, console.error(err));
});
});
// [GET - Available car by id]
app.get('/availability/:id', (req, res, next) => {
const id = req.params.id;
mongoose.connect(keys.mongoURI, function(err, db) {
const cursor = db.model('fancycars');
// [Extract] - one element from the SchemaObject
const doc = cursor.find({ carId: id }, function(err, data) {
res.status(200).send(data);
db.close();
});
});
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log('Listening on Port 3000');
});