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:
2 | "name" : "application-name" , |
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:
2 | "name" : "application-name" , |
Save this file and open a terminal prompt at the project folder and run:
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:
1 | var mongoose = require( 'mongoose' ); |
3 | var teamSchema = new mongoose.Schema({ |
7 | mongoose.model( 'Team' , teamSchema ); |
Here we are doing four things:
- “Requiring” Mongoose so that we can use it
- Defining the schema for a team
- Building a ‘model’ of this schema, called “Team”
- Connecting to the database, in this case a MongoDB database called ‘euro2012′ on the ‘localhost’ server
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:
- Takes a ‘GroupName’ value as a parameter
- Takes a callback function as a second parameter
- Searches the MongoDB database for teams with the provided ‘GroupName’
- 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:
1 | var mongoose = require( 'mongoose' ); |
3 | exports.teamlist = function teamlist(gname,callback){ |
4 | var Team = mongoose.model( 'Team' ); |
5 | Team.find({ 'GroupName' :gname}, function (err, teams) { |
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.
1 | var express = require( 'express' ) |
2 | , db = require( './model/db' ) |
3 | , routes = require( './routes' ) |
4 | , http = require( 'http' ) |
5 | , 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:
1 | exports.index = function (req, res){ |
4 | title: 'Test web page on node.js using Express' , |
5 | pagetitle: 'Hello there' , |
7 | teams: [{ "country" : "England" },{ "country" : "France" },{ "country" : "Sweden" },{ "country" : "Ukraine" }] |
Replacing this with the MongoDB data via Mongoose is surprisingly easy. We need to:
- Require the teams.js model file
- Call the ‘teamlist’ export function, sending it:
- The ‘GroupName’ of teams we are searching for
- The res.render functions as a callback build the page – including the list of teams – when the database query completes
So let’s modify routes/index.js like so:
1 | var teamdata = require( '../model/teams' ); |
3 | exports.index = function (req, res){ |
5 | teamdata.teamlist(strGroup, function (err,teamlist){ |
7 | title: 'Test web page on node.js using Express and Mongoose' , |
8 | pagetitle: 'Hello there' , |
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
Head over to localhost:3000 in your browser and you should see something like this:
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:
So there it is. Mongoose and Express together, greatly simplifying some of the tasks of development in Node.js
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.
No comments:
Post a Comment