How to build a microservice with NodeJs, Express and MongoDB
Published: 2021-05-13 08:21:09

Most of us have gone through tough times where you have a large scale
application which has a bunch of features, API integrations, database
connections, etc. New features and updates get released, and of course you need
to fix the bugs and maintain the code.

Building this real-world application requires dynamic programming, where the
size of the application grows uncontrollably.

This monolith pattern becomes very hard to downsize or simplify the application.
So to run the app smoothly, it is essential to convert the large, homogeneous
structure into small, independent pieces of programs. Similar complexities can
be resolved effortlessly when the NodeJs applications are build on
**microservices, **more so with the Node.js ecosystem.

So I am going to show you how to build the microservices…

> This blog is only for an overview of how to build the services, please visit
> [https://github.com/Nomercy10/ecommerce-micro-services](https://github.com/Nomercy10/ecommerce-micro-services)
for a full functional working microservices demo.

In our example we will be building two microservices, **Users & Orders. **The
idea is very simple, users will place an order. We create the order with all the
required details, and so on.

Here is the list of the features each of these microservice will have

#### Users

* GET all users
* GET user
* Create new user
* DEL user by userId

#### Orders

* GET all orders
* GET order
* GET orders for a user
* Create new order for a user
* DEL an order
* DEL orders for an user

### Tech

* [Node.js](https://nodejs.org/) : evented I/O for the backend
* [Express](http://expressjs.com/) : Fast node.js network app framework
* [MongoDb](https://www.mongodb.com/) : A NoSql database for modern applications

As we build these microservices we will create separate folders for each
microservice. Each folder will have its own package.json and node modules
installed.

Let’s get started…

### Installation

Create `Users` folder and install below dependencies

![](https://cdn-images-1.medium.com/max/1600/1*wDmPGwtWmkeDf41LCZve3w.png)
<span class="figcaption_hack">Users installed dependencies</span>

Info about the dependencies

* **body-parser***:* *It is a Node.js body parsing middleware, it parses incoming
request bodies in a middleware before your handlers and is available under
*`req.body`* property.*
* **axios***: A promise based HTTP client for browser and Node Js.*
* **nodemon***: A tool used for Node Js development as it provides hot-reloading
for any file change.*
* **mongoose***: A MongoDB Object modelling tool designed to work in an
asynchronous environment.*

### Development

Create `Users.js`in the `/Users` folder, this file will be our entry point to
Users microservice.

Load the dependencies

![](https://cdn-images-1.medium.com/max/1600/1*puf0ITJf2bHxqzOVesgmmA.png)
<span class="figcaption_hack">Load dependencies</span>

### Install the MongoDB Node.js Driver

The MongoDB Node.js Driver allows you to easily interact with MongoDB databases
from within Node.js applications. You’ll need the driver in order to connect to
your database and execute the queries described in this Quick Start series.

If you don’t have the MongoDB Node.js Driver installed, you can install it with
the following command.

![](https://cdn-images-1.medium.com/max/1600/1*hfUl7T8uYc-p60FK_D4LBw.png)

### Create a free MongoDB Atlas cluster and load the sample data

Next, you’ll need a MongoDB database. The easiest way to get started with
MongoDB is to use Atlas, MongoDB’s fully-managed database-as-a-service.

[Head over to Atlas](https://www.mongodb.com/cloud/atlas) and create a new
cluster in the free tier. At a high level, a cluster is a set of nodes where
copies of your database will be stored. Once your tier is created, [load the
sample data](https://docs.atlas.mongodb.com/sample-data/).

### Get your cluster’s connection info

The final step is to prep your cluster for connection.

In [Atlas](https://www.mongodb.com/cloud/atlas), navigate to your cluster and
click **CONNECT**. The Cluster Connection Wizard will appear.

The Wizard will prompt you to add your current IP address to the IP Access List
and create a MongoDB user if you haven’t already done so. Be sure to note the
username and password you use for the new MongoDB user as you’ll need them in a
later step.

Next, the Wizard will prompt you to choose a connection method. Select Connect
Your Application. When the Wizard prompts you to select your driver version,
select Node.js and 3.6 or later. Copy the provided connection string as you will
use in the following section.

For more details on how to access the Connection Wizard and complete the steps
described above, see the [official
documentation](https://docs.atlas.mongodb.com/connect-to-cluster/).

### Connect to your database from a Node.js application

Now that everything is set up, it’s time to code! Let’s write a Node.js script
that connects to your database and lists the databases in your cluster.

### Import mongoose client

![](https://cdn-images-1.medium.com/max/1600/1*Elg2AMZsZ-n6-oNEgtNt7w.png)

The `mongoose` client will be used to connect to a MongoDB database. This is an
instance of MongoDb to connect to a cluster, access the database in that
cluster, and close the connection to that cluster.

The first thing after this we need to do is create a constant for our connection
URI. The connection URI is the connection string you copied in Atlas in the
previous section. When you paste the string don’t forget to update `<username>`
and `<password>` to be the credentials for the user you created in the previous
section. The connection string includes a `<dbname>` placeholder.

**Note: **The username and password you provide in the connection string are NOT
the same as your Atlas credentials.

![](https://cdn-images-1.medium.com/max/1600/1*ImrgGjVZcODWYaOE7n-bhw.png)
<span class="figcaption_hack">Connection string URI</span>

Now that we have the URI, we can create an instance of the MongoDB

![](https://cdn-images-1.medium.com/max/1600/1*BZB_wZDkkyOEyv_eqbO3BA.png)
<span class="figcaption_hack">inItialization of MongoDB client and loading the global instance</span>

### Database Models

Now that we have our connection setup, let’s go ahead and create MongoDB data
models. We will be using `mongoose.model` <br>
[Models](https://mongoosejs.com/docs/api.html#model-js) are fancy constructors
compiled from `Schema` definitions. An instance of a model is called a
[document](https://mongoosejs.com/docs/documents.html). Models are responsible
for creating and reading documents from the underlying MongoDB database.

![](https://cdn-images-1.medium.com/max/1600/1*xtBSq2cMu-8kkHN8XF9Ctg.png)

### APIs

For the sake of this blog not becoming too long to read I am going to show only
two APIs. You may create the others I referenced or as many features you want.

*GET all orders for a user API*

![](https://cdn-images-1.medium.com/max/1600/1*nMAaGOPyy65eRaRt2Sw96Q.png)

As you can see above, when we trigger “/users/:uid/” orders we are making an
external API call to Orders microservice and a call the GET API for
“/orders?uid= ”. This way we have communicated between the microservices and
have shared data.

*Create new user API*

![](https://cdn-images-1.medium.com/max/1600/1*DlrhSBuY6nQTuHVhs9t6DQ.png)

In the above example, we are creating a new user. First we create a newUser
object with the response from the request body.<br> We then create a new “User”
instance, a MongoDB data model User instance & pass the “newUser” to it.

We can now use .save() property to save the data to MongoDB. As its a promise
based property we can use `.then` and perform the operation we want to.

**Note: **Note: I am not showing here how to create the microservice for Orders
as it is pretty straightforward and similar to what we have done for Users
microservice. If you still need to see how to implement that, please visit my
github repo link mentioned above at the start of the blog.

Thankyou!

Happy Coding!