Create your own REST API using node.js and Mongo (Part 2 ) Connecting to the database

Welcome to part 2 of the series of how to create your own REST API using node.js and Mongo. In this part I will walk you through the steps to connect with the database. Before I do that I want to encourage you to download Robomongo from their website . Robomongo is a MongoDB management tool which we will use to vizualise the data.

Using Mongoose

To interact with MongoDB we will use Mongoose. Mongoose is an NPM package and is installed by using the following command in your terminal or command prompt window inside your project folder:


Run Mongo

To interact with the database you need to have the MongoDB deamon (as mentioned earlier in this post) running, this is done by using the $ mongod command as shown below:


Minimize (do not close) the window.


For this tutorial we will be using the scenario of a parcel collection service. The database will consist of a parcelschema that contains a collection of all the parcels. Each parcel will have the following fields: itemname :”String”, collected:”Boolean”, collected_at: “Date”

Step 1: Create the JS file

To create the javascript file use a texteditor, I prefer using Brackets.IO but any one will do. Create a file and name it “Parcel.js”

Step 2: Inside our JS file

Inside our file we want to do the following

  1. Load the mongoose package to allow us to communicate with MongoDB.
  2. Use the database called “ParcelTest” or create it if it doesn’t yet exists
  3. Create a schema inside our “ParcelTest” database and call it “ParcelSchema”
  4. Create a model derived from our “ParcelSchema”
  5. Save data to our database
  6. Use Robomongo to see the result

Here is the code:


To run the above file, navigate to your project folder and enter the following in the command window:


You can now view the results of the above code using the Robomongo application. It should look similar to this:


Final Thoughts

That’s it for Part 2 of Creating your own REST API using Node.js and MongoDb. I hope that you have found this guide helpful. Part 3 will be following soon.


One thought on “Create your own REST API using node.js and Mongo (Part 2 ) Connecting to the database

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s