paint-brush
Basic Guide To Building Microservices With MongoDB, NodeJs, And Expressby@rushikesh-mhetre
2,016 reads
2,016 reads

Basic Guide To Building Microservices With MongoDB, NodeJs, And Express

by Rushikesh MhetreJune 4th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Node.js applications are built on microservices, more so with the node.js ecosystem. In our example, we will be building two microservice, Users & Orders. The idea is very simple, users will place an order with all the required details, and so on. We create the order with the details and create a user by userId. The order requests will be sent to a MongoDB client. This client will be used to connect to a cluster that connects to the database in that cluster, that is an instance of mongoose.js.

Company Mentioned

Mention Thumbnail
featured image - Basic Guide To Building Microservices With MongoDB, NodeJs, And Express
Rushikesh Mhetre HackerNoon profile picture

Most of us have gone through tough times where you have a large-scale application that 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 built on microservices, more so with the Node.js ecosystem.

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

This blog is only for an overview of how to build the services, please visit 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 a new order for a user
  • DEL an order
  • DEL orders for a user

Tech

  • Node.js : evented I/O for the backend
  • Express : Fast node.js network app framework
  • MongoDb : 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

Users installed dependencies

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 modeling tool designed to work in an asynchronous environment.

Development

Create 

Users.jsin
the 
/Users
 folder, this file will be our entry point to Users microservice.

Load the dependencies

Load dependencies

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 QuickStart series.

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

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 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.

Get your cluster’s connection info

The final step is to prep your cluster for connection.

In 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.

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

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.

Connection string URI

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

inItialization of MongoDB client and loading the global instance

Database Models

Now that we have our connection setup, let’s go ahead and create MongoDB data models. We will be using 

mongoose.model
Models are fancy constructors compiled from Schema definitions. An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.

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

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 a new user API

In the above example, we are creating a new user. First, we create a newUser object with the response from the request body. 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 it's 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.

Also published at https://medium.com/nerd-for-tech/how-to-build-a-microservice-with-nodejs-express-and-mongodb-73737b6fa868