Skip to content

Instantly share code, notes, and snippets.

@AlexeyHussar
Created November 12, 2017 21:42
Show Gist options
  • Save AlexeyHussar/72122e3f57521c3d4394836f13349187 to your computer and use it in GitHub Desktop.
Save AlexeyHussar/72122e3f57521c3d4394836f13349187 to your computer and use it in GitHub Desktop.
Node_KB
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// Creating bindings todb
mongoose.connect('mongodb://localhost/nodekb', {
useMongoClient: true
});
let db = mongoose.connection;
// Check connection
db.once('open', () => {
console.log('Connected to mongoDB');
});
// Check for db errors
db.on('error', (err) => {
console.log(err);
});
// Init app
const app = express();
// app.use(express.json());
// app.use(express.urlencoded({ extended: false}));
// Bring in Models
let Article = require('./models/article');
// Load View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Applying middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Home route
app.get('/', (req, res) => {
Article.find({}, (err, articles) => {
if (err) {
console.log(err);
return;
}
res.render('index', {
title: 'Articles',
articles
});
});
});
// Add route
app.get('/articles/add', (req, res) => {
res.render('add_article', {
title: 'Add Articles'
});
});
// Add post route
app.post('/articles/add', (req, res) => {
console.log('SOME Shit');
let article = new Article();
article.title = req.body.title;
article.author = req.body.author;
article.body = req.body.body;
article.save(err => {
if (err) {
console.log(err);
return;
}
res.redirect('/');
});
});
// Start server
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment