At first glance, coming to grips with Node.js and MongoDB
can seem both time-consuming and painful. Read on to learn how to wield
these tools quickly and easily. Before getting started, let’s take a
quick look at what this article offers:
- Set up a basic server with Node.js.
- Establish a connection to a MongoDB database.
- Learn how to select records through database calls.
- Finally, build and serve an HTML page with our newly retrieved data.
Installing The Requisite Technologies Link
Let’s get started by setting up a basic Node.js server. If you haven’t already, install Node.js by
following the instructions on How to Node1
or in one of the many articles like it floating around the Web. The
next thing we’ll need is a small MongoDB database; I’ve already created
one for us to test, but if you’d like to create your own, go ahead and
set up an account on
MongoLab32, which will provide you with free hosting for a database of your own (and offer a remarkable scope of paid services).
Now that Node.js is set up and we have a database to connect to,
we’ll need to install MongoJS, which is the library that Node.js uses to
communicate with MongoDB. Luckily for us, when you installed Node.js,
you also installed npm, which makes it a breeze to install MongoJS.
Simply open up a terminal, navigate to the directory where your Node.js
server will be located, and run
npm install mongojs
. The automated package manager will take care of the rest.
Examining The Server Code Link
With the preliminaries out of the way, we can proceed to writing the
actual Node.js server, which we’ll run on localhost for the purpose of
this tutorial. The first thing to do with any Node.js application is
include the modules we’ll be using. In this case, we’ll need the HTTP
module, which is used to create the server, and the MongoJS module,
which we installed earlier:
var http = require("http"),
mongojs = require("mongojs");
Once we’ve included the modules we’re going to use, we need
to connect to a MongoDB database. We need two things to do this. The
first is a MongoDB connection URI. This is provided by default when you
create a server on
MongoLab32, but just for the record, you can find the
specification for MongoDB connection URIs4 in the documentation. The second thing you’ll need is an array of
collections5
(which are “groupings of MongoDB documents”) that you’d like to access
in that database. We just want to access one collection in this case,
but you can stick as many as you’d like in the array.
Once you have the database URI and the array of collections that
you’d like to access, establishing a connection to a database is simple:
var uri = "mongodb://demo_user:demo_password@ds027769.mongolab.com:27769/demo_database",
db = mongojs.connect(uri, ["demo_collection"]);
We’ll need to create our server as well, using the HTTP module:
var server = http.createServer(requestHandler);
When we call the createServer
function, it
expects a function to handle all incoming requests. This is the function
that is called when a browser requests data from the server. The
request-handling function, which we’ve aptly named requestHandler
,
is passed two variables: a request variable, which represents the
browser’s page request, and a response variable, which is the response
we’ll give to the browser. Let’s look at the requestHandler
function:
function requestHandler(request, response) {
The first thing we’ll do in the request handler is tell the
browser what format our response will be in — HTML, plain text or
something else entirely — so that it knows how to handle the data it
gets.
response.writeHead(200, {"Content-Type": "text/html"});
The next thing we’ll do — and this is the interesting bit —
is query the database we linked to earlier, so that we have information
to work with. We’ll pass a JSON object to the find
function, specifying the property that we’d like the returned records to share. The find
function returns a cursor to the documents returned by our query; this cursor is iterable and contains all of the data we need.
db.demo_collection.find({"color": "red"}, function(err, records) {
When Things Go South Link
Within the find
function, we’re given two variables to work with: err
and records
. The err
variable contains any data about an error, if one has occurred. First,
we check whether any errors have been thrown while attempting the
database query. If no problem occurred, then we carry on. But if one
did, then we wouldn’t have any data to work with and the rest of the
function would be useless, so we’d just log the issue and return
immediately; there’d be no point in executing the rest of the function.
if(err) {
console.log("There was an error executing the database query.");
response.end();
return;
}
OK, now that we’ve got our data, which is contained in the cursor records
,
we need to iterate that data and build an HTML string for the server to
give to the browser. We’ll create a variable to hold our HTML string,
and then iterate through our records. Then, we’ll build a string for
each document and append it to the main HTML string:
var html = '
Vehicles with a red finish
',
i = records.length;
while(i--) {
html += 'Name: '
+ records[i].name
+ '
Number of wheels: '
+ records[i].wheels
+ '
Color: '
+ records[i].color;
}
Finally, once we’ve finished iterating through all of the
records, we’ll write our response by generating an HTML string with a
quick while
loop. Now, Node.js offers many more methods for
displaying HTML, the most common of which is by serving up a static
page (often with a framework such as Express), but generating a string
is a quick and dirty way to display some basic HTML.
This particular HTML string contains the data for the entire page. So, once we call response.write
, we’ll know that the client has all of the information it needs, and we’ll end the response so that it can load the page.
response.write(html);
response.end();
Wonder Twins, Activate! Link
That’s pretty much all there is to creating a basic HTML
server with Node.js and using that server to connect to a MongoDB
database. The last thing to do is tell the server to listen at whatever
port we specify:
server.listen(8888);
Executing this code will fire up a local server that you can access at port 8888 (localhost:8888
in your browser).
Conclusion Link
As you can see, setting up a Node.js server and connecting
it to a MongoDB database is remarkably simple, at least compared to the
majority of technologies that compete with this power duo. Of course,
setting up security and proper error-handling can take a little more
work, but resources for working with Node.js and MongoDB are growing
rapidly. Together, the tools offer a quick yet enormously flexible
solution that’s taking the server-side programming world by storm.
Further Reading Link
(il, al)
Comments
Post a Comment