78 lines
2.0 KiB
JavaScript
78 lines
2.0 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://192.168.0.252:27017'
|
|
|
|
/* View Engine */
|
|
app.set('view engine', 'ejs');
|
|
|
|
/* Style */
|
|
app.use(express.static(__dirname + '/public'));
|
|
|
|
|
|
/*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 }));
|
|
app.use(bodyParser.json());
|
|
|
|
/* 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))
|
|
|
|
|
|
})
|
|
|
|
/* Update */
|
|
app.put('/quotes', (req, res) => {
|
|
quotesCollection.findOneAndUpdate(
|
|
{ name: 'Marcus' },
|
|
{
|
|
$set: {
|
|
name: req.body.name,
|
|
quotes: req.body.quotes
|
|
}
|
|
},
|
|
{
|
|
upsert: true
|
|
}
|
|
)
|
|
.then(result => res.json('Success'))
|
|
.catch(error => console.error(error))
|
|
})
|
|
|
|
}) |