Menu Search
Jump to the content X X
SmashingConf London Avatar

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf London, dedicated to all things web performance.

An Introduction To Node.js And MongoDB

Node.js is a rapidly growing technology that has been overtaking the world of server-side programming with surprising speed. MongoDB is a technology that’s revolutionizing database usage. Together, the two tools are a potent combination, thanks to the fact that they both employ JavaScript and JSON.

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.

A Detailed Introduction To Node.js And MongoDB

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 MongoLab, which will provide you with free hosting for a database of your own (and offer a remarkable scope of paid services).

Further Reading on SmashingMag: Link

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 MongoLab, but just for the record, you can find the specification for MongoDB connection URIs6 in the documentation. The second thing you’ll need is an array of collections7 (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://",
    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.");

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 = '<h2>Vehicles with a red finish</h2>',
    i = records.length;

while(i--) {
    html += '<p><b>Name:</b> ' 
         + records[i].name 
         + ' <br /><b>Number of wheels:</b> ' 
         + records[i].wheels 
         + '<br /><b>Color: </b>' 
         + 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.


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:


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)

Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

↑ Back to top Tweet itShare on Facebook

Elliot is a freelance JavaScript developer located somewhere in the general vicinity of Providence, Rhode Island. When not working, he enjoys programming, writing, and listening to music. He is a coffee drinker and a cat person. He is the owner of and writer for Hey, JavaScript!

  1. 1

    Bob Cochran

    May 24, 2014 1:09 am

    Thanks for the great article. Can you suggest techniques for accessing data sourced from two MongoDB collections which have to appear on the same web page presented to the client. For example, vehicles with a red finish are in the demo_collection collection. You might want to display a photo of each vehicle which is stored in a separate vehicle_photos collection, and on that same web page, say right under the text line showing the name, number of wheels and color.

    • 2

      Hi Bob,

      Assuming both collections are in the same database, it’s as simple as including the name of the second collection in the array you’re passing to the “mongojs.connection” function, like this: “db = mongojs.connect(uri, [“demo_collection”, “vehicle_photos”]);”

      Then when you want to access that data, simply call, for example, “db.vehicle_photos.find(…)”.

      Did that answer your question?

      • 3

        Bob Cochran

        May 28, 2014 12:52 am

        Thank you very much Elliot, I’ll give this a try. I have a lot to learn, and this is a good introduction to Smashing Magazine for me.

  2. 4

    Ja mon god b great article. thank ya mon for the nice lists to more resources too. I’ll be studying this in the mornin. You give good start on my journey. word.

  3. 5

    Can you pl show how to connect with Oracle?

  4. 6

    Ranjeet Singh

    May 25, 2014 7:09 am

    thanks sir …very useful article

  5. 7

    Mathieu HAYS

    May 27, 2014 2:58 pm

    I would recommend to use Mongoose as well. When you use a new framework and a new way of thinking your code, it might be useful to have this data-modeller to restrict yourself from doing silly mistakes.
    I found it more straight-forward to use.

  6. 8

    Matthew Trow

    May 27, 2014 5:45 pm

    Just a heads-up on mongodb … you may want to read this excellent article before ploughing ahead:

  7. 9

    Chris Chang

    May 28, 2014 6:15 pm

    Thanks for the shoutout Elliot! We have free Sandbox plans up to 500MB for folks to get their feet wet with Node.js and MongoDB in the cloud. Feel free to write us at [support at mongolab dot com] if you need help!


  8. 10

    Curious why you chose `mongojs` module instead of the official driver? –

    As Mathieu mentions above, I also think mongoosejs is a great for object modeling with Node.js and MongoDB.

  9. 11

    In your `while` loop, don’t forget to close your paragraph tag.

  10. 12

    Excellent introduction to Using node and mongodb.

  11. 13

    Coding Defined

    July 31, 2014 2:01 am

    For more information about modules in Nodejs, check this

  12. 14

    abdelhakim lahrach

    September 29, 2014 12:05 am

    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.
    you can learn sql her :

  13. 15

    Code does not work if zero rows are returned. Ez to fix. Thanks for the example.

  14. 16

    Is there somewhere to get the entire example file? The way it’s quoted in bits and pieces is hard to follow.

  15. 17

    Mark S.: I got it to work, but found a small tweak necessary. Please see:

    Elliot Bonneville: Thank you for this tutorial! It was a great quick start to MongoDB under Node.js. Exactly what I was looking for!


↑ Back to top