An Introduction To Node.js And MongoDB

Advertisement

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

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

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

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 = '<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.

response.write(html);
response.end();

Wonder Twins, Activate!

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

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

(il, al)

Footnotes

  1. 1 http://howtonode.org/how-to-install-nodejs
  2. 2 https://mongolab.com/welcome/
  3. 3 https://mongolab.com/welcome/
  4. 4 http://docs.mongodb.org/manual/reference/connection-string/
  5. 5 http://docs.mongodb.org/manual/reference/glossary/#term-collection
  6. 6 http://docs.mongodb.org/manual/installation/
  7. 7 http://blog.nicoversity.com/2013/04/tutorial-mongodb-2-4-2-on-os-x-using-homebrew/
  8. 8 http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
  9. 9 http://mongodb.github.io/node-mongodb-native/

↑ Back to topShare on Twitter

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!

Advertising
  1. 1

    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.

    1
    • 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?

      0
      • 3

        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.

        1
  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.

    -6
  3. 5

    Can you pl show how to connect with Oracle?

    -3
  4. 6

    thanks sir …very useful article

    0
  5. 7

    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.

    http://mongoosejs.com/

    2
  6. 8

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

    http://www.sarahmei.com/blog/2013/11/11/why-you-should-never-use-mongodb/

    3
  7. 9

    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!

    -Chris@MongoLab

    1
  8. 10

    Curious why you chose `mongojs` module instead of the official driver? – https://www.npmjs.org/package/mongodb

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

    0
  9. 11

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

    0
  10. 12

    Excellent introduction to Using node and mongodb.

    1
  11. 13

    For more information about modules in Nodejs, check this http://www.codingdefined.com/

    -1
  12. 14

    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 : http://insaneitskills.com/sql-tutorial/

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top