56 lines
1.4 KiB
JavaScript
56 lines
1.4 KiB
JavaScript
|
const express = require('express');
|
||
|
const app = express();
|
||
|
const bodyParser = require('body-parser');
|
||
|
const res = require('express/lib/response');
|
||
|
const MongoClient = require('mongodb').MongoClient
|
||
|
const mongoDb = 'mongodb://mymongodb'
|
||
|
|
||
|
/* View Engine */
|
||
|
app.set('view engine', 'ejs');
|
||
|
|
||
|
|
||
|
/*Mongo Connection*/
|
||
|
MongoClient.connect(mongoDb, (err, client) => {
|
||
|
if (err) return console.error(err);
|
||
|
console.log('Connected to Database');
|
||
|
const db = client.db('crud');
|
||
|
const quotesCollection = db.collection('quotes');
|
||
|
|
||
|
|
||
|
/* Express requests */
|
||
|
app.use(bodyParser.urlencoded({ extended: true }));
|
||
|
|
||
|
/* Creating the Server*/
|
||
|
app.listen(4000, function () {
|
||
|
console.log('listening on 4000');
|
||
|
})
|
||
|
|
||
|
//Send to my index.html
|
||
|
//app.get('/', (req, res) => {
|
||
|
// res.sendFile(__dirname + '/index.html');
|
||
|
//})
|
||
|
|
||
|
/* Create */
|
||
|
app.post('/quotes', (req, res) => {
|
||
|
quotesCollection.insertOne(req.body)
|
||
|
.then(result => {
|
||
|
console.log(result);
|
||
|
res.redirect('/');
|
||
|
})
|
||
|
.catch(error => console.error(error))
|
||
|
})
|
||
|
|
||
|
/* READ */
|
||
|
app.get('/', (req, res) => {
|
||
|
const cursor = db.collection('quotes').find().toArray()
|
||
|
.then(result => {
|
||
|
console.log(result)
|
||
|
/* Ejs view engine*/
|
||
|
res.render('index.ejs', { quotes: result });
|
||
|
})
|
||
|
.catch(err => console.error(err))
|
||
|
|
||
|
|
||
|
})
|
||
|
|
||
|
})
|