Built.io Blog

Express your business logic in node using MongoDB


In my previous blog post, Say hello to node express, we built a simple node app using express. In the app, we didn't use any business logic; we just output a "hello world". In this post we will add business logic to node by using MongoDB.

NOTE: In this post implement a basic level of MongoDB and Node.js (using express.js as framework) interaction. This post assumes you are using a Windows environment.

Download MongoDB

For those of you who are not familiar with MongoDB, please review its website. You can also download MongoDB from its website. Just select the appropriate production release for your system. For Windows 8 on a 64-bit processor, you will need "64-bit *2008R2+". After you download the appropriate zip, unzip it to a temp directory.

Make a directory where you want to store Mongo, such as c:mongo or c:program filesmongo.

Set Up the Data Directory

MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is C:datadb. You can create this folder using the Command Prompt. Go to the C:directory and issue the following command sequence:

<code>md data 
md datadb</code>

You can specify an alternate path for data files using the -- dbpath option to mongod.exe.

Start MongoDB

To start MongoDB, execute from the Command Prompt:


You may specify an alternate path for datadb with the dbpath setting for mongod.exe, as in the following example:

<code>C:MongoDBbinmongod.exe --dbpath d:testMongoDBdata</code>

You can also set environment variable's paths so that you can globally use MongoDB globally. Copy this path and set it as the path in environment variables:


Connect to MongoDB

Connect to MongoDB using the mongo.exe shell. Open another Command Prompt and issue the following command:


You will get the following response if everything is set up properly:

<code>MongoDB shell version: 2.4.8 
connecting to: test</code>

Congratulations! You now have MongoDB up and running, and connected it to with the client. Don't worry about connecting to: test because that's just the default database Mongo decides to use when one doesn't specify a database. In fact, it only creates the "test" database when you first add a record. Let's get started!

Just create an app in express. If you're not sure how, take a look at my previous post.

You'll notice that the express installation routine created a file called package.json in your testapp directory.

Open this up in a text editor and it will look like this:

  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  "dependencies": {
    "express": "3.4.6",
    "jade": "*"

This is a basic JSON file describing our app and its dependencies. We need to add a few things to it: specifically, calls for MongoDB and Monk. Update your JSON file to the following:

<code> "dependencies": {
    "express": "3.4.6",
    "jade": "*",
    "mongodb": "*",
    "monk": "*"

Now thaat we've defined our dependencies, we're ready to go. Note that the asterisks(*) tells NPM to "just get the latest version" when running the installer, which we're about to do. Return to your command prompt, change directories to your testapp directory, and enter this:

<code>C:nodetestapp>npm install</code>

It's going to print out a ton of stuff. That's because it's reading the JSON file we just edited and installing all the stuff listed in the dependencies object (yes, including Express ñ we installed the top level stuff using the ñg flag, but we still have to install some necessary code for this particular project).

Once NPM has run its course, you should have a node modules directory which contains all of our dependencies for this tutorial.

Create a database

To create a record in MongoDB for our app, we have to create a database first. Creating a database in MongoDB is not difficult, just type following command in the MongoDB console:

<code>use testapp</code>

We set up a database as "testapp" so we can use the command testapp.

Although we've set the database as testapp, just like with "test", nothing actually exists yet. The database will be created automatically when we add some data. Let's start off by doing this in the Mongo client.

The coolest thing about MongoDB is that it uses JSON for its structure. If you're not familiar with JSON, you'll need to do some reading; that's outside the scope of this tutorial.

Add some data

Let's add a record to our collection. For the purposes of this tutorial, we're just going to have a simple database of usernames and emails.

Our data format will thus look like this:

 "id" : 1234,
 "username" : "harshal",
 "email" : "harshal.joshi@raweng.com" 

MongoDB will automatically create an ID assignment. Enter the following:

<code>db.user.insert({ "username" : "harshal","email" : "harshal.joshi@raweng.com" })</code>

Please note the following db stands for our database, which we defined as testapp. The user is our collection. We did not need to create create this collection because MongoDB automatically created it when we first added content.

Assuming everything went well, you should see Ö nothing. That's not very exciting, so type this in mongo console:


 "id" : ObjectId("5202b481d2184d390cbf6eca"),
 "username" : "harshal",
 "email" : "harshal.joshi@raweng.com" 

Your ObjectID will be different because Mongo automatically generates those. That's all there is to writing to MongoDB from a client app. If you've ever worked with JSON services before, you are probably thinking, "Wow, that's going to be easy to implement on the web."

Now that we've created a record in our user collection, we're going to list this record from node.

Get started by adding these three lines at your app.js:

<code>var express = require('express'); 
var routes = require('./routes'); 
var user = require('./routes/user'); 
var http = require('http'); 
var path = require('path'); 
// New Code 
var mongo = require('MongoDB'); 
var monk = require('monk'); 
var db = monk('localhost:27017/testapp'); </code>

This code enables your app to connect to MongoDB, using Monk. Our database is located at localhost:27017/testapp. In case you didn't know, 27017 is the default port for a MongoDB. If for some reason you've changed the port, you'll need to reflect this in your code and replace:

<code>app.get('/users', user.list);</code>

with this:

<code>app.get('/users', user.list(db));</code>

We can set the root URL for the app, by replacing:

<code>app.get('/', routes.index);</code>


<code>app.get('/', user.list(db));</code>

This line says that when a user navigates to the /users or root ('/') action, we should pass the db variable (our database object) to the /users or root route. Since we don't have a /users route yet, so it's time to create one. Open routes/user.js and replace this code:

<code>exports.list = function(req, res){
 res.send("respond with a resource"); 


<code>exports.list =  function(db){
  return function(req, res){
    var collection = db.get('user');
      res.render('list_user', {
        "userlist" : docs

Oh, it seems complicated! All it's really doing, though, is running a wrapper function to which we pass our db variable, and then doing a page render.

We've then created a wrapper function that which accepts a db variable and renders the page. We then tell it to use the user collection find and then return results as the variable docs. Once we have those documents, we then render a list of user (which will needs a corresponding Jade template.) This creates a userlist variable to work with, and passes the database documents to that variable.

It's now time to create a Jade template to show the user list. Create a new Jade file named list_user.jade with the following code:

<code>extends layout
block content
        User List
        each user, i in userlist
                a(href="mailto:#{user.email}")= user.username</code>

This code pulls the set of documents, and for each entry named user in the loop, gets the corresponding email and username values from the object and adds them to the html file.

We've also got the count ñ i ñ handy in case we need it, though in this instance we don't.

We're all set. Save this file, and let's restart the Node.js server. Go to the command line, set your directory as C:nodetestapp kill app.js if it's still running by typing Ctrl-C.

Start your app by typing:

<code>C:nodetestapp>node app.js</code>

Now open your browser and head to http://localhost:3000

You will see a list of users from this database.

Writing to a database

Writing to a database is not particularly difficult. You need a route that accepts a POST, rather than a GET. You could use AJAX but we'll stick to a standard post-and-show-results approach.

We are going to show two basic text boxes. Let's add a new route that can redirect us correctly to the desired location. Open up app.js and add a new route below your previously defined route:

<code>app.get('/', user.list(db)); 
app.get('/users', user.list(db)); 
// New Code 
app.get('/users/new', user.new);</code>

As with all app.get requests, we need to adjust the route to know what to serve up. Open /routes/user.js and add the following:

<code>exports.new= function(req, res){
    res.render('new_user', { title: 'Add New User' });

Now we just need a template, so we will create a new one for this. Create a new_user.jade under the views directory and add following code to it.

<code>extends layout
block content
    h1= title
        input#inputUserName(type="text", placeholder="username", name="username")
        input#inputUserEmail(type="text", placeholder="useremail", name="useremail")
        button#btnSubmit(type="submit") submit</code>

Here we created a form with the ID "formAddUser". The method is POST, and the action is add_user. Beneath that, we've defined our two inputs and a button.

If you restart your node server and go to http://localhost:3000/new, you will see the form you created. We still need to integrate the POST action in node to handle this form submission, so let's add this one.

Create your db function

Add one POST route in app.js:

<code>app.get('/users/new', user.new); 
app.get('/', user.list(db)); 
app.get('/users', user.list(db)); 
app.get('/users/new', user.new); 
// New Code 
app.post('/users', user.add_user(db));</code>

Note that you're using app.post, not an app.get.

Go back to /routes/user.js and let's create the insertion function. This is a big one, so I've commented the code pretty thoroughly. Here it is:

<code>exports.add_user = function(db){
  return function(req, res) {
    // Get our form values. These rely on the "name" attributes
    var userName = req.body.username;
    var userEmail = req.body.useremail;
    // Set our collection
    var collection = db.get('user');
    // Submit to the DB
      "username" : userName,
      "email" : userEmail
    }, function (err, doc) {
      if (err) {
        // If it failed, return error
        res.send("There was a problem adding the information to the database.");
      else {
        // If it worked, set the header so the address bar doesn't still say /adduser
        // And forward to success page

Obviously, in the real world you would want more validating, error-checking, and the like. It's important to check for duplicate usernames and emails, for example, and to vet that the email address is likely a legitimate entry, but this will work for now.

After successfully adding the user to the database, we forward the user back to the userlist page, where they should see their newly added user. Are there smoother ways to do this? Absolutely. This tutorial was designed to use bare-bones functionality. Now, let's go add some data! We are officially reading and writing from a MongoDB database using Node.js, Express, and Jade.

From here, there's a million different directions you could go. I recommend you try Mongoose, another Mongo-manipulation package for Node/Express.

Subscribe to our blog