MongoDB, Express, AngularJS (1.6) and NodeJS (MEAN) Part 2

Ethan Nwankwo
CloudBoost
Published in
6 min readAug 14, 2017

--

Introduction

This is a continuation of the MEAN Series, if you feel the need to start from the basics, go ahead and explore the part 1 of the series.

In this part, we will setup the server file and define routes to serve our application on the browser. We will also look at some angularJS concepts and how they work together with nodeJS on the backend to make our life easier.

We’ll be writing our javascript code using ECMAScript 6 (es6), so expect lots of const, let, map and arrow functions. Feel free to check out a resource on es6 if these terms sound strange or you feel your javascript is getting rusty, hopefully you will get some motivation from learning about all the cool stuff we can do using es6. :)

Step 3: Express Server setup and MongoDB connection

Let’s create our app entry point. To do this, we create a server.js file in the project root directory with the following code snippet:

// server.jsconst express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const router = express.Router();
// Connect to mongoDB databaseconst mongoURL = 'mongodb://<dbuser>:<dbpassword>@<host>:<port>/<database-name>';mongoose.connect(mongoURL);// Routing// Configure port
const port = 8080;
// Listen to port
app.listen(port);
console.log(`Server is running on port: ${port}`);

Replace <dbuser>, <dbpassword>, <host>, <port>and <database-name> with your mongodb credentials.

Note:

  • If you’re using mongodb locally, your host will most likely be localhost and unless you have a username and password set, your connection string may simply just look like:
mongodb://localhost/<dbname>
  • It automatically creates the database with the name specified in the connection string when you perform an insert query.
  • If you’re using the online version on mongoDB provided by mlab, you’ll need to log into your account, create a database and a database user, and get the connection string which usually looks like:
mongodb://<dbuser>:<dbpassword>@dsXXXXX.mlab.com:XXXX/<db-name>

We will store the connection string along with other sensitive data in an environment variable in the next tutorial to prevent compromising the security of our application and database. However for this part, we will allow them in the server.js for simplicity, but hey, don’t try this in production. :)

Next thing is to start the application on the terminal using:

node server.js

This will log the following on the terminal if successful:

Server is running on port: 8080

If you see this message, then the server connection to mongodb was successful and our app started successfully. We now proceed to adding some routes and serving some static pages.

Step 4: Server/Backend Routes

In this step, we create the backend route for the application to enable it communicate with our server. To achieve this, we are going to modify our server.js file created earlier and add the following snippet just below Routing:

// server.js. . .// Routingrouter.get('/', (request, response) => {
response.status(200).send({message: 'Hello World!'})
});
//Set app to use express backend router
app.use(router);
. . .

Now we restart our application, open up a browser and navigate to http://localhost:8080/

On your browser window, you should see the message:

{"message":"Hello World!"}

If you see this displayed, our backend route works. awesome!!!

Now we create html files to be rendered on the browser. To do this we run the following unix command from the project root directory:

mkdir public && touch public/index.js && touch public/index.html

This will create a public directory and create index.js and index.html files in it.

Our directory structure should look like:

> node_modules
> public
-- index.html
-- index.js
-- package.json
-- server.js

In the index.js file we add the following snippet:

// index.jsangular.module('angularApp', [])
.controller('indexCtrl', function($scope) {
// Initialize variables $scope.name1 = ''; this.name2 = ''; $scope.greeting1 = `Hello ${$scope.name1}`; this.greeting2 = `Hi ${this.name2}`;
})

Observe that we are defining two variables that seem to be doing the exact same thing but look slightly different, there has been several opinions on the best way to define variables and methods in an angularjs controller, $scope has been around for sometime, while this just joined the party after angular 1.2. I use both depending on how I’m feeling. Both was also used on angularJS component doc. Which ever one you choose to use, so far I think they both achieve same results. Although whenever you use this, you will have to instantiate the controller as a variable in the view like: ng-controller=”indexCtrl as app” as used below, while if you’re using $scope, you only need ng-controller=”indexCtrl”.

If you feel fascinated by the $scope vs this topic, feel free to research further into it and let me know in the comment section on your findings. For now, we’ll focus on their usage. I will use this for most part of this tutorial because I feel like it :). Actually because I think it reduces the chances of confusing pure text in html as angular variables.

In our index.html file, we add the following snippet:

<!doctype html><html ng-app="angularApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="index.js"></script>
</head>
<body> <div ng-controller="indexCtrl as app">
<input
type="text"
ng-model="name1"
placeholder="Using $scope variable name"
/>
<br />
<input
type="text"
ng-model="app.name2"
placeholder="Using this variable name"
/>
<br /><br />
<h2 ng-if="name1 != ''"> Hello {{name1}} </h2>
<br />
<h2 ng-if="app.name2 != ''"> Hi {{app.name2}} </h2>
</div>
</body>
</html>

Now we update our backend route to render static pages in the public directory. To do this, we add the following snippet to our server.js file just above Routing defined earlier:

//  Serve static filesapp.use(express.static('public'));

We also update our initial backend route to point to/api .

Now our files look like shown below:

server.js:

index.js:

index.html:

Once we have the files above, we go ahead and restart our application and navigate to http://localhost:8080/ on the browser.

We’ll find empty input fields where we can enter text and get hello/hi messages displayed on the browser.

We can also navigate to http://localhost:8080/api and access our app API route.

AngularJS Concepts:

The script above featured a few angular concepts. Let’s talk a bit about them.

We will not dive too deeply into these concepts so that we won’t get lost in theoretical stuff. But if you’re feeling motivated, I’ll recommend you take a moment to research on them. I’ll just point out a few here, the ones relevant to our case study.

Modules:

An angular module is a container for the various parts of our application. It is defined with the angular.module keyword (i.e angularApp in our case).

A module divides an angular app into smaller reusable components. All controllers and functions in the app must belong to a module and a module can be dependent on other modules, this is achieved using a concept referred to as Dependency Injection (DI).

Every web page view in the app can be instantiated with a module using the ng-app directive as used in our index.html above.

Directives:

These are DOM manipulators, they tell the angular compiler which attributes to attach to the DOM element. They start with an “ng-” prefix.

In the example above, we saw directives such as ng-app, ng-controller, ng-model and ng-if. There are others, such as: ng-view, ng-show, ng-options, ng-repeat, ng-src, ng-click, ng-change, ng-form, ng-init, ng-switch, ng-href, etc.

These directives are simply awesome. With them, we can make the DOM act in whatever way we want. We can even create our own directives, how cool is that :)

Directives can also be specified in camelCase. Check out angular docs for a list of the directives and all the cool stuff we can do with them.

2-way data binding:

This remains one of the coolest features of angularJS, the ability to synchronize data between the model and the view, which implies that any change on one side immediately affects the other. We notice that in our app, when we enter a value in the input field, it immediately reflects on the browser, that is 2-way binding and it is achieved using the ng-model directive.

Summary

We have seen how to connect express server to mongodb, create backend routes and also serve static files. We have also seen some of the cool stuff we can do with angularJS and how easy it is to manipulate DOM operations using angular directives. All these are just a tip of the iceberg, we can do a whole lot more with MEAN, we’re just getting started.

In our next tutorial, we will focus on making database calls and performing create, read, update and delete (CRUD) operations using RESTful API. We will also look at how to automate our tasks and set up webpack to bundle our dependencies, we will use nodemon to listen for changes and hot-reload the server. Observe that we used a CDN to import angularJS into our project, that will change with webpack. We will also store our application sensitive data in .env to prevent security compromise.

Feel free to drop your comments, suggestions and/or questions and I’ll be happy to get back to you.

Resources:

AngularJS, NodeJS, ExpressJS, MongoDB

Interested in cryptocurrency investments? check out my post on buying and investing.

Visit my profile for other publications I’ve made.

--

--