#Blog app
###Objectives:
- Understand express basics
- Build a model in express
- Build routes in express
- Complete RESTful blog app in express
Install mongodb
brew update
brew install mongodb
To start up an app, run this command:
npm init
Run through the process to start up an application. Then add these following dependencies:
"dependencies" : {
"express" : "~4.7.2",
"mongoose" : "~3.6.2",
"morgan" : "~1.2.2",
"body-parser": "~1.5.2",
"method-override": "~2.1.2",
"jade", "latest"
}
express
Express brings in the express module into our app
mongoose
Mongoose is a Node.js library that provides MongoDB object mapping similar to ORM with a familiar interface within Node.js. If you aren't familiar with Object Relational Mapping (ORM) or, Object Data Mapping (ODM) in the case of Mongoose, this means is that Mongoose translates data in the database to JavaScript objects for use in your application.
morgan
Logs all the requests to the console
bodyParser
Populates the request.body with the value of the POST parameters
methodOverride
Simulate DELETE and PUT. With this we can use app.delete and app.put in express instead of using app.post all the time
// the app
app.put('/users/:id', function (req, res, next) {
// edit your user here
});
###Create an app.js
$ touch app.js
###Heroku up!
$ heroku create
$ heroku addons:create mongolab
Now let's go and look our our heroku.com account and see the new app we created. Click the heroku addon for mongolabs
When we get there, create a new user
Remember that user name and password.
Starting in app.js, bring in all our dependencies
var express = require('express'),
app = express(), // create app with express
path = require('path'),
mongoose = require('mongoose'), // mongoose
morgan = require('morgan'),
bodyParser = require('body-parser'),
methodOverride = require('method-override');
Connect mongodb
mongoose.connect('YOUR MONGO LINK HERE');
Create our model
var Blog = mongoose.model('Blog', {
title: String,
content: String,
createdAt: {
type: Date,
default: Date.now
}
});
Set our view engine to jade
// View engine. Sets name to value
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
Set our logger, body parser, and methodOverride
// Use morgan for our routing
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
At the very bottom, add
// Listen on 3000
app.listen(3000);
console.log("App listening on port 3000");
Now test our application to see if it works
$ node main.js
It should respond with
App listening on port 3000
Create the Index path
// INDEX
app.get('/', function(request, response){
Blog.find(function(error, blogs){
if(error){
response.send(error);
}
response.render('blogs/index', {title: 'Blogs', blogs: blogs});
});
});
###In the same directory, create a views folder. Create a file called layout.jade then a blogs folder. Then, create edit.jade, index.jade, new.jade, show.jade
In layout.jade
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
In index.jade
block content
div
h1= title
a(href='/blogs/new') Write a new blog
each blog in blogs
li
h3
a(href='blogs/#{blog._id}')= blog.title
p= blog.content
span= blog.createdAt
Now test our application to see if it works
$ node main.js
###Your index should now work!
###New & Create in app.js
// NEW
app.get('/blogs/new', function(request, response){
response.render('blogs/new', {
title: 'New blog'
});
});
// CREATE
app.post('/blogs', function(request, response){
var blog = new Blog();
blog.title = request.body.title;
blog.content = request.body.content;
blog.save(function(error){
if(error){
response.send(error);
}
response.redirect('/');
});
});
In our new.jade, add
extends ../layout
block content
h1= title
form(name='add-blog' method='POST' action='/blogs')
p Title:
input(type='text' placeholder='Title' name='title')
p Body:
textarea(placeholder='Write your blog' name='content')
p
button(type='submit') Add blog post
a(href='/') Back to home
Now test our application to see if it works
$ node main.js
###Your new and create now work!!
###Show & Destroy
In app.js
// SHOW
app.get('/blogs/:id', function(request, response){
Blog.findOne({_id: request.params.id}, function(error, blog){
if(error){
response.send(error);
}
response.render('blogs/show', {title: blog.title, blog: blog});
});
});
// DESTROY
app.delete('/blogs/:id', function(request, response){
Blog.findByIdAndRemove(request.params.id, function(error){
if(error){
response.send(error);
}
response.redirect('/');
});
});
In our show.jade
extends ../layout
block content
h1= title
p= blog.content
ul
li
a(href='/blogs/#{blog._id}/edit') Edit this blog
li
form(method='POST' action='/blogs/#{blog._id}?_method=DELETE')
button(type='submit') Delete blog
a(href='/') Back to home
Now test our application to see if it works
$ node main.js
###Your show and destroy now work!
###Edit & Update
In app.js
// EDIT
app.get('/blogs/:id/edit', function(request, response){
Blog.findOne({_id: request.params.id}, function(error, blog){
if(error){
response.send(error);
}
response.render('blogs/edit', {title: blog.title, blog: blog});
});
});
// UPDATE
app.put('/blogs/:id', function(request, response){
Blog.update({_id: request.params.id}, {
title: request.body.title,
content: request.body.content
}, function(error, blog){
if(error){
response.send(error);
}
response.redirect('/');
});
});
In edit.jade
extends ../layout
block content
h1= title
form(method='POST' name='edit-blog' action='/blogs/ #{blog._id}?_method=PUT')
p Title:
input(type='text' name='title' placeholder='Title' value='#{blog.title}')
p Content:
textarea(name='content' placeholder='Content' value='')= blog.content
p
button(type='submit') Update blog
a(href='/') Back to home
Now test our application to see if it works
$ node main.js
###Your edit and action now work!
###We have created a Full CRUD app in expressJS