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.
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:
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
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
- Create a schema inside our “ParcelTest” database and call it “ParcelSchema”
- Create a model derived from our “ParcelSchema”
- Save data to our database
- 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:
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.