The Switch To Node, Express,And MongoDB Part 3: Installation and the code

In part one of this series we discussed the choices we evaluated when switching from parse.com to a new backend stack.  Part two discussed the middleware we used and had a brief explanation of what each piece does.  In this final section we will give some of the code used to make the routes and middleware work.

A few more details to give some background.  This particular application runs on a Linode instance.  Linode is a great tool for production and development because the pricing is straight forward and quite reasonable.  They have even released a new $5/month plan that has some generous specs and at that price you can't really go wrong.    We use CentOS7 as the Linux distribution, and while this doesn't really matter it is worth noting because the terminal commands in this post are CentOS specific.  With that out of the way lets get started from the top. 

 

If you are interested in following along with this then you will at this point need to have a server ready to go either at Linode or another provider of your choice.  The next few steps will show how to install MongoDB, Express, and Node.

First ssh into the server using terminal. 

~ssh user@your.ip.address

user should be changed to the user you have set up or if you have not yet set up a user then it should be changed to root.  your.ip.address should obviously be the IP address of your VPS.  If you are using Linode it can be found on your Linode dashboard by clicking the server and choosing the remote access tab.

Enter your password.

Great.  So now you are in.  We can start to install the software needed to get the backend up and running.  I like to start with MongoDB.  The first thing we need to do is install the MongoDB repository.  Paste this command into terminal to create the repository file.

~ sudo vi /etc/yum.repos.d/mongodb-org.repo 

This will open a terminal based text editor where we will need to paste some information to allow the server to find the MongoDB installation source.  To get the code to paste in, visit the MongoDB site and get the repo code. It looks similar to this...

[mongodb-org-3.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.2.asc

After this has been pasted into the terminal based text editor you need to save and close the file. To do this you need to first press the Escape key.  This will take you out of insert mode.  To save and close now press :wq.  This should close the terminal editor and return you to the previous screen.  If you are having any issues with this you may want to look at this page with basic vi editor commands. 

If you want to see if you did this part correctly you can see a list of the repositories in the yum repo list with this terminal command.

~yum repolist 

The output of this command should contain

mongodb-org-3.2/7/x86_64 MongoDB Repository

Of course your version numbers may be different.  


Now we can install MongoDB from the repo we just added with this terminal command.

~sudo yum install -y mongodb-org 

After the installation has completed we can go ahead and start the MongoDB service with this terminal command.

~sudo service mongod start 

Now that we have MongoDB installed and running we can install the rest of what we need.  As a good starting point I like to update all of the packages on the server.  This simple terminal command will do the trick.

~yum update 

 This may take a while depending on your connection.

When that is complete we can install Node.  We will first have to install the EPL repository where we will fetch node.js from.  It is as simple as this terminal command...

~sudo yum install epel-release 

Now we can install node with this command.

~yum install nodejs 

When this is done you can make sure that node is installed by checking its version with this command.

~node --version 

You now have MongoDB, Node, and npm installed on your server.  The next step is to create a package.json file to specify what else needs to be installed and then continue on to install those packages. Below is a simplified version of the package.json file we will use.

{
  "name": "Some Name",
  "version": "1.0",
  "description": "Some description",
  "main": "app.js",
  "author": "Your Name",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.15.2",
    "ejs": "^2.5.3",
    "express": "^4.14.0",
    "mongoose": "^4.4.20",
    "morgan": "^1.7.0",
    "nodemon": "^1.11.0",
    "path": "^0.12.7"
  }
}

Now that you have your package.json file saved with some dependencies , we can install them with npm.  

Back in terminal make sure you are in the same directory as the package.json file and use this terminal command.

~npm install

This will install all the dependencies you included in the package.json file.  When it is done we can start writing some code to handle actual HTTP traffic from either a website or a mobile application.


We separate the code for the backend into 3 distinct files.  

  • app.js
  • routes.js
  • models.js

This makes changes to the code on the backend a little more manageable.  

 

Here is what is in the app.js file.

'use strict';

var express = require("express");
var app = express();
var routes = require("./routes.js");
var logger = require("morgan");
var path = require("path");

app.use(logger("dev"));
app.use(express.static(path.join(__dirname, 'public')));

var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/DB_Name");

var db = mongoose.connection;

db.on("error", function(err){
    console.error("Connection error:", err);
});

db.once("open", function(){
    console.log("Database connection was successful");
});

app.use("/",routes);

var port = process.env.port || 80;

app.listen(port, function(){
    console.log("Express server is listening on port ", port);
});

This file starts the application and connects to the database.  You can name the database (DB_Name) whatever you like.  The application will create the database if it doesn't exist on launch.  There are a few lines here that we do not necessarily need at this point but we can leave them in as they will not affect anything we are trying to do here. You can also change the port to whatever you like but I went with 80 for this example so that you can simply visit the IP address of your server without specifying a port to see if it is working.  To get our application running that is all we need in the app.js file.  To test if it is working correctly you can go back to terminal at enter this command.

~node app.js

You should get the 2 console.log lines in the terminal.

Database connection was successful
Express server is listening on port 80

Congratulations.  You now have a server up and running connected to your database.  It is time to add some routes to make something interesting happen. Lets make the routes.js file.

 

Let's start out with a simple route that shows a webpage. Paste this into your routes.js file.

'use strict';

var express = require("express");
var router = express();
var bodyParser = require('body-parser')
var ejs = require('ejs');
// set the view engine to ejs
router.set('view engine', 'ejs');
router.set('views', __dirname + '/views');
router.use(cookieParser());

//render the home page
router.get('/', function (req, res) {
    res.render('index');
});

module.exports = router;

Admittedly  this is a ridiculously simple routes.js file, but it is the beginning of whatever you want to do with this stack.  In this case we want to show an HTML page when someone visits our IP address.  To make this actually work we will need a folder called "views" in the same directory with a file called index.ejs inside that views folder.  Go ahead and make that folder now as well as a file called index.ejs.  The index.ejs file can contain any HTML page you want.  For a way to get started quickly you can just paste in this HTML code.

<!Doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Simple Test Page</title>
</head>
    <body>
        <h1>It's working</h1>   
    </body>
</html>

Your app should be all set up to show this page now.  To check you have everything in place you should have the following inside your user or root folder on the server.

  • app.js file
  • routes.js file
  • views folder
    index.ejs file inside views folder

If you have all of this in place you can test out your app by going to terminal.  If the app is still running you will have to restart it by holding Control and pressing X.  You can now start the application  with the same command as before. 

~node app.js

Now if you go to the IP address of your server in a browser you should get the HTML Page you created.

 

Conclusion

Getting this stack up and running for web development or as a backend for your mobile app is quite simple in the end.  I saw many tutorials out there that missed a step or didn't explain things quite as well as I needed to get it all up and working.  Hopefully this is not one of those for you.

 

If you are using this for a backend of a mobile app then you would just change the res.render to res.json and pass back some data.   

Is it easier then parse.com, firebase, or some other Backend As A Service?  Nope!  Definitely not..  Is it really satisfying to know that if my service of choice goes out of business I can simply drop my code into any VPS I want?  ABSOLUTELY!.  

 

If I did miss some steps that confused you along the way please let me know in the comments and I will be sure to update the information. If you need sample code for iOS or Android also just let me know.

Jude Machin

Troubled Pixel, 4701 120th Blvd, Lubbock, TX, 79424, United States