Express_Crud_Example/server.js

78 lines
2.0 KiB
JavaScript
Raw Normal View History

2022-01-28 22:33:42 +01:00
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const res = require('express/lib/response');
const MongoClient = require('mongodb').MongoClient
2022-01-28 22:53:32 +01:00
const mongoDb = 'mongodb://192.168.0.252:27017'
2022-01-28 22:33:42 +01:00
/* View Engine */
app.set('view engine', 'ejs');
2022-01-28 22:53:32 +01:00
/* Style */
app.use(express.static(__dirname + '/public'));
2022-01-28 22:33:42 +01:00
/*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 }));
2022-01-29 22:57:19 +01:00
app.use(bodyParser.json());
2022-01-28 22:33:42 +01:00
/* 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))
})
2022-01-29 22:57:19 +01:00
/* 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))
})
2022-01-28 22:33:42 +01:00
})