Nodejs and MongoDB, A Beginner’s Approach
This is not a book and I didn’t try to sell a book to you.
The term “A Beginner’s Approach” reflects my self when finding a hard way out to connect Nodejs to MongoDB. There are lots of libraries available to use when connecting Nodejs to MongoDB. If you were trying to make your feet wet, and that’s what I’m doing until today, you probably want to try this approach. I can’t promise anything but at least, you will not get a headache.
First, read about Nodejs. After that, MongoDB. If you’re already familiar with it, skip it and install both on your system. There maybe vary depending on your system. If you use Mac and Homebrew (or MacPorts), you’re lucky. Just do this:
$ brew install node
to install Nodejs, and:
$ brew install mongodb
$ sudo port install mongodb
to install MongoDB.
Okay, here’s the fun part. Oh wait, we need to install one more additional driver to connect from Nodejs to MongoDB. I’ve picked node-mongodb-native by christkv and I recommend you to install it too. It’s easy.
$ npm install mongodb
Now we’re ready to go.
To prepare a connection to MongoDB, you can create variables that define the database and its server, like this one:
and then instantiate a database client:
Next, you may want to define the action for insert, remove, update, and show the data. Here’s mine.
Now, the final step is to open the connection and do what you want with your already-defined action above.
You’ve noticed that there is a
'test_insert' is your collection name (you can go with different name though). You can think a collection just like a table in SQL database, but without a relation (that’s why we often call it NoSQL because it has no relationship like SQL does).
These codes are far from perfect. I simplify it for the sake of, surprise surprise, simplicity and easy to understand. I uploaded the source code to my Github too. So if you want to try a little bit
further, you can do whatever you like, based on my code, to explore more about Nodejs and MongoDB.
Any comments or questions are definitely welcome.
Update: I forgot to mention that for the sake of simplicity, I’m not including a callback following some operations above. Christkv, the author of the native driver I’ve used here, has give us a clue on his comment below so I just want to say that if you want (and ready) to know more about callback, please read here.