How to create a basic API with NodeJS and Express part 2

Image for post

In my previous article we discussed installing setting up and then installing the necessary packages to create a basic API using node JS and Express, within this article I will discuss setting up a MongoDB schema using Mongoose as well as creating a database using MLab and connecting your Mlab database to your API project.

Firstly, if you haven’t, sign up to MLab.com (MLab is a website that hosts MongoDB databases) https://mlab.com/, if you already have simply login, what you first need to do is click the button labelled “create new” on the top right, this will then bring you to a screen with 3 options “amazon web services”, “Google cloud platform” and “Microsoft Azure”. Choose “Amazon web services” as well as ensure that the option for “Sandbox” is clicked as well as this is a free option.

Image for post
Image for post

After clicking “continue” click on either of the regions.

Image for post
Image for post

Next you will need to give your database a name.

Image for post
Image for post

After entering a valid database name (I believe the name “test” isn’t valid) click continue/finish and you will then be redirected to a list of your current MongoDB deployments, click on the database you just created.

Your screen will look like this, to be able to access your MLab database from NodeJS you will need to create a user for that database, so click on the tab that says “Users” and after this click on the button with the text “Add database user”.

Image for post
Image for post

You will then be prompted with a modal that asks you to enter a database user name and password, take a note of these credentials as you will to insert them into a file within your project later. Also, leave the checkbox “Make read-only” unticked.

Image for post
Image for post

And we are now done with setting up a MongoDB database in MLab, give yourself a pat on the back!

Now I will go over a few of the main concepts of MongoDB

MongoDB is a no-SQL database which stores its data in a document and key value pair format, a NOSQL database contains collections so you could have one collection for users and other for information about toothpastes, these collections will then contain documents, which are the (BSON — a binary version of JSON objects which allows the MongoDB documents to be traversed easily)objects that get stored in the database. Every document within a collection can be of a different size and contain more or less fields than other documents, an example of a document is below.

{_id: "test12345"name: “Alex”,age: 24,place: “England”,hobbies: [“Learning Russian”, “Going to the gym”]}

Whenever a mongoDB document is created it is given key of “_id” which uniquely identifies that document so is acting as a primary key.

Now that you have setup a user for your database collection we can now traverse back to our project and within the root of your project create a folder called schema and another folder called “credentials” (in my project I have created a folder called secretstuff) then within this folder create a file called “credentials.js”, this will contain the username and password that you setup for your MongoDB database.

Now within this file (“credentials.js”) type in the following:

module.exports = {
username:'yourusernamehere',
password:'yourpasswordhere'
}

“module” is a variable which contains current module context and “exports” is an object that exposes whatever you have assigned to be exposed, and in this case it is the username and password you set in MLab.

The next step is to go back to your file “server.js” and require both the username and password so we can make a connection to our MongoDB database.

var username = require('./secretstuff/secrets').username;var password = require('./secretstuff/secrets').password;

To require both the username and password we will need to put the filepath of your folder inside of “require” (with your project it may be different), and on variable use dot notation to reference “username” and with the other variable use it to reference “password”.

What you then need to do is go back to your MLab database and find a link unique to your database, an example of this link is below.

Image for post
Image for post
In your database copy the link under the heading “To connect using a driver via the standard MongoDB URI”

Paste this into a variable called mongoDB, you will then need to replace the prefilled username and password with the username and password you required previously, an example of this code is below.

var username = require('./secretstuff/secrets').username;var password = require('./secretstuff/secrets').password;app.use(bodyParser.json());//support parsing of application/x-www-form-urlencoded post dataapp.use(bodyParser.urlencoded({ extended: true }));var mongoDB = `mongodb://${username}:${password}@ds353957.mlab.com:53957/russianlanguageapp`

As you can see I have used template literals to interpolate the username and password into the mongodb connection string.

NOTE: The code

app.use(bodyParser.json())

Tells express that when you send a request to the API you want it to be in JSON format.

In addition the code

app.use(bodyParser.urlencoded({ extended: true }));

“extended:true” allows greater flexibility with the data you are sending to the API, i.e. if you set the value to “extended:false” then you will not be able to post nested objects, whereas, if you set to true, then you can, the main reason for this is “extended:false” uses the library “querystring” and doesn’t let you create nested objects from your query string, whereas, “extended:true” uses the “qs” library which enables you to create a nested object from your query string.

Furthermore, you will now need to invoke the “connect” method of the mongoose module using the code below

mongoose.connect(mongoDB,{useNewUrlParser:true});

“useNewUrlParser:true” is necessary as otherwise you will use the old string parser and be shown a message in the console regarding the current URL string parser being deprecated and removed in the future, so it is best practice to insert this into the method parameter.

However, for now comment out the line

mongoose.connect(mongoDB,{useNewUrlParser:true});

We will now create a root endpoint for our application, and to do this we will need the instance of our express package “app” and to enter the code.

app.get("/",function(req,res){res.send({message:"Default api"})
});

This process is called “routing”, routing is how an apps endpoints respond to a client request, we have used “app.get” to define that this a route that will handle get requests (The HTTP method GET) to the API through the endpoint “/” i.e. root route. Once the application realises that we are sending a request to the endpoint “/” the application will then run the code found within the callback function of the route and in this case is just responding to us with a message saying “Default API” with the parameter “req” representing the request object and “res” representing the response object.

“res.send” is a method that sends the “http response” and can be a string, object, buffer or array. A few examples of these are below.

res.status(400).send('Sorry, you are unauthorized')
res.send({ test: 'my json' })
res.send('<h1>Big heading</h1>')

To actually run and test whether this endpoint works we will need to implement the “listen” method of the Express instance “app”.

The “listen” method begins a UNIX socket and will then listen for connections on that port, and in our case on localhost will be 3000. An example of the code with a callback function is below, with the first argument “port” representing the variable we created in the previous article.

app.listen(port,function(){
console.log("REST API listening on port: " + port);
});

Now after entering the “listen” method and the root route “/”, you should enter the command “npm start”, to start up the server.

Now if you haven’t already download an “API development environment” such as “Postman” or “Insomnia”

I have recently just started using “Insomnia”, and in the URL tab enter the text

http://localhost:3000/

We only need to put “/” after the localhost link because that is the location of our root route, you should see some sort of output like the image below.

Image for post
Image for post

As you can see I have made a GET request on the url “http://localhost:3000/” and received a response saying “Default api” and in the code above you will see that this is the message we set to response to the user once the root route command was called.

Now that you have created the root route you should try and create other routes adhering to REST principles with different response messages and call them using Insomnia or POSTman. In my next article I plan on going a lot deeper into MongoDB and creating our own schemas to then insert them into our database that we made in this tutorial using the HTTP verb “POST”.

As always thank you very much for reading this article and if there is anything you think i can improve upon in terms of my writing style, giving examples etc I’m always open to suggestions to help myself get better and provide bette quality articles for people to read and learn from, have a great day :)

Software Developer in the UK. With a keen passion for React Native.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store