Image for post
Image for post
Use Node.

Tutorial — Building a Simple Blog With Node, Express & Mongo

Update: Note: At the time of writing this tutorial I used express 4.16.3 technologies change over time so this tutorial may vary slightly from newer versions of express. If you run into any issues, I recommend a quick google of the error, and if you’re still stumped, comment the issue. Thanks!

Following this tutorial you will make an app with anode server that will store our data and serve that data to views. The concepts in this tutorial will be a great jumping off point for diving deeper into the node ecosystem.

When I first started to learn node, I became confused really quickly. Not only did I have to learn node itself, but it seemed there was an endless amount of other libraries that I would also have to learn in order to get anywhere. With this tutorial I am seeking to give beginners a really easy step-by-step walkthrough of setting up a simple node blog. I want programmers who are new to writing javascript to feel comfortable following along and hopefully feel more comfortable in the node environment by the end. So let’s get started.
Side note: I use a Mac and will be referencing commands and tools used in that environment. Just giving you a heads up.

The Essentials

Before we begin, you need to have node installed on your computer. I don’t need to write another article on this, so just go here: http://blog.teamtreehouse.com/install-node-js-npm-mac

Open up your terminal. And navigate to wherever you want to create your project. I have a projects/ folder that I use personally, but it doesn’t matter. Now you need to make a for this project, and in this folder you need to create a file: app.js

cd ~/projects
mkdir node-blog
cd node-blog
touch app.js

Okay, I hope I haven’t lost you just yet. Now we need to initialize our project with npm so that we can manage the dependencies that we will be using.

npm init

This will prompt a few questions which will set up your package.json. The only important thing here is that when asked about entry point use: app.js

Here we go

Okay, now we are ready to start building. To get a webserver up and running fast we will use express. So before writing the code run:

npm install express@4.16.3 --save

This will save the dependency locally so we can use it in our app.
Now we write some code in app.js

// Setup
var express = require('express');
var app = express();
// Listen
app.listen(3000, () => {
console.log('Server listing on 3000');
})

What this does is the app is set to express() and that app listens on the port specified. In this case 3000. So now when we fire up the app we can view our app on http://localhost:3000

To start the app, in your terminal run:

node app.js

You should be met with the log: “Server listening on 3000”, which is neat and all but let’s serve up a page so our web app has a view.

For this tutorial I’ve decided to use the simplest rendering engine that I know of: EJS. You actually can serve static html files if you want to without using an engine, but that would be boring. So follow along and we will have a view up shortly.

In the terminal:

npm install ejs --save

And now back in our code we need to add the following lines:

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

Make sure you do this below the initialization of app
Next we need to add a route, to serve the page.

app.get("/", (req, res) => {
res.render('index');
});

So this is setting up a route for “/” or the root directory. When this route is hit it will render the index view, which reminds me, we don’t have that yet.

By default EJS looks for views in a view directory, so let’s create one and lets add an index view while we are at it

mkdir views
touch views/index.html

In index.html let’s just write up a plain old html file for now, don’t worry we will be adding the dynamic stuff soon enough. In the meantime we will add a form that will post to our app.

<html>
<head></head>
<body>
<h1>Node Blog</h1>
<form action="addpost" method="POST">
<textarea name="body"></textarea>
<input type="submit" value="Add Post" />
</form>
</body>
</html>

And just to make sure you are following along, this is what your app.js should look like this:

// Setup
var express = require('express');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// Routes
app.get("/", (req, res) => {
res.render('index');
});
// Listen
app.listen(3000, () => {
console.log('Server listing on 3000');
})

Go ahead and start the app again now and then visit http://localhost:3000
It looks like we are getting somewhere.

Now we need to store the posts from the form. As you can see in index.html our form is posting to “addpost”. So we need to make a route for it and we need to make a schema so that we can store the data when we get it.

We are going to use mongo for the database. First we are going to install mongo, then we are going to add the data folder where the dbs are stored, then we are going to give that folder the correct permissions. It’s not as hard as it sounds. In your terminal run the following:

brew install mongo
mkdir -p /data/db
sudo chown -R `id -un` /data/db

That’s it. Now when we run mongod in the terminal, mongo will be running and ready to use. So actually, go do that now. Open up a separate window and run mongod

We will be using mongoose to handle our connection to mongo. So in your terminal:

npm install mongoose --save

And in our app.js:

var mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/node-blog")

Note: mongo by default connects on 27017. The last part of the connection url is the name of our database, here I have decided to use “node-blog”

While we are at it we may as well include the body parser so that our application can parse the post data body. We will be using the parsed data to store in our schema. Back in the terminal:

npm install body-parser

And in our application:

var bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true}))

Now we need to create a schema, and a model for that schema. We do this by creating a new mongoose schema and defining the parameters. Once we have a schema we assign a mongoose model to that schema.

var postSchema = new mongoose.Schema({ body: String });var Post = mongoose.model('Post', postSchema);

Finally, we create the “addpost” route that stores this information. We will redirect to our root route when this is complete and we will return an error if necessary.

app.post('/addpost', (req, res) => {
var postData = new Post(req.body);
postData.save().then( result => {
res.redirect('/');
}).catch(err => {
res.status(400).send("Unable to save data");
});
});

Now back in our root route we need to grab the data before sending it to the view:

app.get("/", (req, res) => {
Post.find({}, (err, posts) => {
res.render('index', { posts: posts})
});
});

With our data going to our view now, we just have to show the posts that have been saved. We do this using EJS. Back in your index.html:

<html>
<head></head>
<body>
<h1>Node Blog</h1>

<% for(let i = 0; i < posts.length; i++) { %>
<article>
<p><%= posts[i].body %></p>
</article>
<% } %>
<form action="addPost">
<textarea name="body"></textarea>
<input type="submit" value="Add Post" />
</form>
</body>
</html>

And you are done. make sure mongo is running and then run node app.js vistit http://losthost:3000

And there you have it. A simple blog built on node, mongo, express and ejs. If you have any issues compare your code to mine below:

app.js

// Setup
var express = require('express');
var app = express();
var mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/node-blog")
var bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true}))
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
var postSchema = new mongoose.Schema({ body: String });var Post = mongoose.model('Post', postSchema);// Routes
app.get("/", (req, res) => {
Post.find({}, (err, posts) => {
res.render('index', { posts: posts})
});
});
app.post('/addpost', (req, res) => {
var postData = new Post(req.body);
postData.save().then( result => {
res.redirect('/');
}).catch(err => {
res.status(400).send("Unable to save data");
});
});
// Listen
app.listen(3000, () => {
console.log('Server listing on 3000');
})

Thanks for reading! I hope this get’s you started using Node on your projects.

https://twitter.com/andyhartnett12

Programmer — Writer. @andyhartnett12

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store