Node.js, Express and Mongoose

Previously we have used Node.js with Mongoose, and Express with hard coded data. Now it is time to bring it all together using Node.js, Express, MongoDB and Mongoose.

Start with the Express project

I created a new copy of the Express project from the previous tutorial, source of which you can find on GitHub.

This has got our simple route and single page of info, but the data list for the teams is hard-coded as a JSON object in the ‘routes/index.js’ file.

Install Connect and Mongoose

The easiest way to do this is to use the package.json file in the root of the project and npm. This method allows you to install all of the modules you need at once, or you can add some in later, like we are doing now. This is a useful habit to get in to.

Opening up the package.json file you should see something like this:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app"
  },
  "dependencies": {
    "express": "3.0.0rc5",
    "jade": "*"
  }
}

We are going to add a couple of lines to the ‘dependencies’ section to include Connect and Mongoose, so that it now looks like this:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app"
  },
  "dependencies": {
    "express": "3.0.0rc5",
    "jade": "*",
    "connect": "*",
    "mongoose": "*"
  }
}

Save this file and open a terminal prompt at the project folder and run:

npm install  

This will read the dependency list from the package.json file and install any new packages into the project.

Setting up the Mongoose connection and defining the data model

In the root directory of the application we’ll create a ‘model’ folder to contain our database connection, schema information and any interactions with it.

In this folder we will start off by creating a file db.js with the following content:

var mongoose = require('mongoose');  
var teamSchema = new mongoose.Schema({  
  country: String,
  GroupName: String
});
mongoose.model('Team', teamSchema);  
mongoose.connect('mongodb://localhost/euro2012');  

Here we are doing four things:

  1. “Requiring” Mongoose so that we can use it
  2. Defining the schema for a team
  3. Building a ‘model’ of this schema, called “Team”
  4. Connecting to the database, in this case a MongoDB database called ‘euro2012′ on the ‘localhost’ server

The schema and model should both be familiar if you’ve seen my Mongoose & Node.js tutorial.

Getting data from the database

In the ‘model’ folder create a file teams.js. We will use this to search the database for teams with a given ‘GroupName’ and return a JSON response. If you had other ‘team’ related queries they could be placed in here – e.g. all data about a given team.

Our file will need an export function that:

  1. Takes a ‘GroupName’ value as a parameter
  2. Takes a callback function as a second parameter
  3. Searches the MongoDB database for teams with the provided ‘GroupName’
  4. Send the database output to the callback function.

We created a Team.find() function last time round, so by taking that, bringing in the Team model as a local variable and  requiring Mongoose, teams.js should look something like this:

var mongoose = require('mongoose');  
exports.teamlist = function teamlist(gname, callback) {  
  var Team = mongoose.model('Team');
  Team.find({
    'GroupName': gname
  }, function(err, teams) {
    if (err) {
      console.log(err);
    } else {
      console.log(teams);
      callback("", teams);
    }
  }); // end Team.find 
}; // end exports.teamlist

Establish the Mongoose connection

Mongoose is designed to have a reusable connection created on application startup. It also makes sense to only define the schemas once. So as we start our app by calling app.js this is where we need to require db.js. Let’s add it in to the require section at the top of the file, just after requiring Express.

var express = require('express'),  
    db = require('./model/db'),
    routes = require('./routes'),
    http = require('http'),
    path = require('path');

(Snipped for brevity, keep the rest of the app.js file intact).

Displaying the data on the webpage

When we created the static data version in Express we hardcoded the JSON object into routes/index like so:

 exports.index = function(req, res) {
   var strGroup = "D";
   res.render('index', {
     title: 'Test web page on node.js using Express',
     pagetitle: 'Hello there',
     group: strGroup,
     teams: [{
       "country": "England"
     }, {
       "country": "France"
     }, {
       "country": "Sweden"
     }, {
       "country": "Ukraine"
     }]
   });
 };

Replacing this with the MongoDB data via Mongoose is surprisingly easy. We need to:

  1. Require the teams.js model file
  2. Call the teamlist export function, sending it:
    1. The GroupName of teams we are searching for
    2. The res.render functions as a callback to build the page – including the list of teams – when the database query completes

So let’s modify routes/index.js like so:

 var teamdata = require('../model/teams');
 exports.index = function(req, res) {
   var strGroup = "D";
   teamdata.teamlist(strGroup, function(err, teamlist) {
     res.render('index', {
       title: 'Test web page on node.js using Express and Mongoose',
       pagetitle: 'Hello there',
       group: strGroup,
       teams: teamlist
     });
   });
 };

Again, this is very similar code to that used in my earlier Mongoose tutorial, but here the Express res.render() function is a much neater way of building the resulting web page.

See it working

In terminal cd into the root folder for this site and run it by typing

node app  

Head over to localhost:3000 in your browser and you should see something like this:

Testing Mongoose and Express

If you’ve kept the console.log statements in the code, you should see verification of the data being retrieved from the database. Similar to this:

Mongoose confirmation in terminal

So there it is. Mongoose and Express together, greatly simplifying some of the tasks of development in Node.js

Get the source code

The source code for this and my other tutorials on Node.js is available on GitHub here: https://github.com/simonholmes/knowing-node/

Now that we have the building blocks of Node.js, Express, MongoDB and Mongoose in place, next time we’ll start building a web app we can actually use in the real world.