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 https://robomongo.org/ . 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.

Tutorial

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

Load the mongoose package to allow us to communicate with MongoDB.

Use the database called “ParcelTest” or create it if it doesn’t yet exists