justjs: node.js tutorials

New here? You might want to start at the beginning.

5/15 '12

Getting Started, Part II: Discovering MongoDB

Storing Stuff: It's Kinda Important!

Node is up and running already. So I could skip along and start showing you things node can do. But I have this terrible, old-school habit of writing apps that store stuff. And storing stuff requires a place to put it. And I like to be able to store that stuff close by, especially when I'm developing a new app and testing lots of changes. I don't want to wait for some far-away cloud database server to respond sluggishly to an app that's running on the Mac in front of me.

So before we dig into Node, let's finish assembling our new toys by installing the MongoDB database.

Why MongoDB?

First: MongoDB speaks JavaScript. Note the title of this blog. 'Nuff said.

Second: MongoDB is much faster than old-school SQL databases.

Third: MongoDB has a more robust set of features than most "NoSQL" databases. When you consider how flexible and friendly MongoDB is, it's really more of a "NewSQL" database. Folks who have experience with MySQL and other old-school databases will be more comfortable with MongoDB than with most other alternatives.

I would sum up MongoDB's personality thus: "we like delivering cool features. We just don't like things that are clunky, tedious, inconsistent and slow."

Installing MongoDB

For starters, head on over to the MongoDB site and click Downloads. You'll be given a choice of many versions. Too many! But don't worry, it's easy to figure out which one is right for your needs. Just look in the first row. This is the latest stable, production version of MongoDB.

Second, you'll see versions for two kinds of Macs: those running a 32-bit kernel, and those running a 64-bit kernel. And this is a problem, because many of us have no idea whether our Macs are running a 32-bit or a 64-bit kernel.

Fortunately there's a quick way to find out:

1. Click the Apple menu.

2. Pick "About This Mac."

3. Click "More Info."

4. Scroll down and pick "Software."

5. On the right, look for "64-bit Kernel and Extensions." If you see it, congratulations, you have a 64-bit kernel. Download the 64-bit version of MongoDB. If not, you have a 32-bit kernel. Download the 32-bit version.

A warning for ambitious folks: on a 32-bit system, a MongoDB database can't store more than 2GB of data. That's still plenty for developing and testing your app (I have a 32-bit kernel on my own Mac as of this writing). As long as you're not storing originals of photos directly in MongoDB or running a Facebook clone in production, this is unlikely to be a dealbreaker for you.

Configuring MongoDB

Now that you've downloaded MongoDB, you'll need to unpack the archive and move the software to an appropriate place where you can easily find it with terminal commands. No, it's not quite as convenient as it could be. But it's not hard, either. Just follow these steps:

1. Open the archive. It'll be extracted to a new folder inside your Downloads folder. The folder will be called something like "mongodb-osx-i386-2.0.5".

2. Move that folder to your home folder (the house icon in Finder).

3. For convenience, rename that folder to just "mongodb".

4. Create a new, empty folder inside "mongodb" called "data".

5. Open up your .profile file again (remember this from the previous post?) and add one more folder to your PATH environment variable. With the new folder added at the front, it'll look like this:

PATH=~/mongodb/bin:/usr/local/bin:/other/stuff:$PATH

(That tilde at the beginning is terminal-ese for "my home directory.")

6. Start up a new Terminal window. (An old window won't see the new PATH setting.)

7. Type:

mongod --dbpath=mongodb/data &

And press Enter. (I'm going to stop reminding you to press Enter after terminal commands by now. I'm sure you've caught on that it is always appropriate.)

If all goes well, you'll see a message like this:

Tue May 15 22:47:14 [websvr] admin web console waiting for connections on port 28018
Tue May 15 22:47:14 [initandlisten] waiting for connections on port 27018

MongoDB is now running in the background. It'll keep running until you restart your computer. If you want, you can add an alias to your .profile that allows you to restart it easily at any time:

alias startmongo="mongod --dbpath=mongodb/data &"

Now you can just type startmongo at the terminal prompt to start MongoDB at any time.

You shouldn't need to stop mongodb. But if you really want to, you can do so with this command:

killall mongod

Speaking Fluent MongoDB

So MongoDB is up and running. Big whoop. What can we do with it?

For starters, we can talk to it! Let's create a database and put some information in it. MongoDB comes with a convenient command line tool for use at the Terminal prompt. It makes it very easy to get started and just play around with Mongo queries.

Open a second Terminal window, stretch it to the width of the screen and type:

mongo myfirsttest

You should see:

MongoDB shell version: 2.0.5
connecting to: myfirsttest
>

We've connected to MongoDB and created a new database called myfirsttest, just like that! MongoDB just creates a database on the fly the first time you ask for it.

Now let's insert some data - how about a blog post? Try pasting this command at the > prompt:

db.posts.insert( { 'title': 'My first post', 'body': 'This is my first blog post.', 'created': new Date() });

We just inserted a new blog post "document" into a "collection" called posts. Notice we didn't have to create the posts collection. Or define a schema for a table. Nope, we just wrote some JavaScript! It's very simple JavaScript, too: an object with title, body and 'created' properties. The first two are just plain old text, and the third is a Date object. MongoDB knows what to do with all of them.

Now let's retrieve our blog post back:

db.posts.find();

This should print:

{
  "_id" : ObjectId("4fb318583cda994bf5f23726"),
  "title" : "My first post",
  "body" : "This is my first blog post.",
  "created" : ISODate("2012-05-16T03:00:40.648Z")
}

This is exactly what we inserted- well, almost! The _id property is automatically created for us by MongoDB. It will always be unique, so it's a convenient way to fetch this particular post again. And the created property was stored in a standard international format. We'll see how easy it is to manipulate and format these dates with JavaScript in a future post. (Actually, you can see it in action in the upper right corner of this post.)

When we don't want the post anymore, we can remove it:

db.posts.remove({ _id: new ObjectId("4fb318583cda994bf5f23726") });

Since we have just one post, we could have written:

db.posts.remove();

That command deletes all posts from the collection.

We could also have written:

db.posts.remove({ 'title': 'My first post' });

Removing documents by id, though, is a better choice if you want to be sure you are not removing any other documents with the same title.

Ladies and Gentlenodes, Start Your Engines!

That's it- we've installed both node.js and MongoDB, and we're ready to do some real work with Node! Beginning in the next post I'll start showing off real Node-powered websites and examining the code that powers the blog you're reading. There's nothing quite like autobiographical programming!

blog comments powered by Disqus