MongoDB is one of the most popular No-SQL databases in the developer community today. Instead of SQL objects, No-SQL databases allow developers to send and retrieve data as JSON documents. In this blog, we will demonstrate how to connect to MongoDB using Mongoose and MongoDB Atlas in Node.js. Let’s get started!
In this blog, we will cover:
- What is MongoDB?
- What is MongoDB Atlas?
- What is Mongoose & why?
- A quick comparison of MongoDB & Mongoose
What is MongoDB?
MongoDB is an open-source document-oriented database that can store a large amount of data while also allowing you to work with it very efficiently. It is classified as a NoSQL (Not only SQL) database because data in MongoDB is not stored and retrieved in the form of tables.
It is well-known among developers not only for the efficiency and smoothness with which it handles data, but also for its driver support for popular languages such as Node.js, PHP, Java, Go, .Net, Ruby, Scala, C#, C, C++,& Python.
Top companies such as Facebook, Google, Adobe, Nokia, and many others have chosen MongoDB as their database management system.
What is MongoDB Atlas?
MongoDB Atlas is a multi-cloud database service developed by the same team that created MongoDB. Atlas simplifies database deployment and management while providing the flexibility required to build resilient and performant global applications on the cloud providers of your choice.
What is Mongoose?
Many people who learn MongoDB are introduced to it through the widely used Mongoose library. “elegant MongoDB object modeling for Node.js,” according to the description of Mongoose.
Mongoose is a MongoDB ODM (Object Data Modeling) library. While using an Object Data Modeling (ODM) or Object Relational Mapping (ORM) tool is not required for a great MongoDB experience, some developers prefer it. Mongoose is used by many Node.js developers to assist with data modeling, schema enforcement, model validation, and general data manipulation. And Mongoose simplifies these tasks.
MongoDB comes with a flexible data model by default. This makes future MongoDB database changes and updates very simple. However, many developers are accustomed to rigid schemas.
Mongoose imposes a semi-rigid schema from the start. Developers must define a Schema and Model when using Mongoose.
A Quick Comparison of MongoDB & Mongoose
In this hands-on, we will see how we can connect to MongoDB using Mongoose and MongoDB Atlas in Node.js. We will begin with creating a new directory on the local machine. Initializing the app in the directory, we will install the required packages for the implementation. Verifying the installation of the packages, we will create a code file thereby putting in the code to connect to the database. Navigating to the MongoDB Atlas, we will demonstrate how to sign up and create a new database.
We will then configure a new user and add the IP so that we can access it in our code. Altering the parameters in our code, we will then move on to create a model which is a database schema. Exporting the schema we will then create route files with the API calls to add a record in the database and to list all the inserted records. We will then spin up the server and navigate to the postman application to hit the insert API. On successful execution, we will run the get API followed by testing out the same for multiple records.
- Express: It is basically a back-end web application framework for Node.js designed for building various web applications and APIs.
- Mongoose: It is a MongoDB object modeling tool designed to work in an asynchronous environment.
Create a new directory on your local machine.
Right-click in the newly created directory and click on git bash here.
Run the below command:
Give a name for the application and for the other options select the default configuration.
Select yes for the final configuration. Confirm the created JSON object.
Now, open the directory into a code editor.
You will see a package.json file created.
Now, we need to install express. Execute the below command in the console:
npm install express --save
On success, you will see the following message on the console.
Now we need to install a mongoose. To do so, run the below command:
npm install mongoose --save
On successful installation, you will see the following message on the screen.
Open the package.json file, file installation of express and mongoose packages.
Create a new file in the directory with the name server.js.
Import the express mongoose and router packages using the code shown below.
Create an object for express to be able to use its functionalities.
In the below code, we will be able to connect to the MongoDB database.
Now we need to create a cluster on mongo DB atlas. To do so click on the below link:
Fill in the details.
Or you can scroll down and sign up with Google.
On successful registration, you will be navigated to the following page. Click on build a database.
You can choose the different types as per your choice. For the demo purpose, we will be using the free one which is the shared type. Click on create below the shared type.
Select the cloud provider as per your choice.
Scroll down and select the region for the database.
Leave the other settings as default and click on create a cluster.
On successful creation, you will be navigated to the below screen.
Enter a username and for the password, you can either create your own password or you can click on auto-generate secure password. Click on copy to copy the generated password. Store the password in a safe place.
Click on Create User and on success, you will see the new user added.
Scroll down and select my local environment. Enter the IP you require that should be able to access the cluster. Click on Add Entry.
Finally, scroll down and click on finish and close.
You will see the new cluster created. Now, click on Connect.
Choose Connect your application.
Select the driver as Node.js and the version as required. Copy the connect string as shown in the image below.
Now, move back to the server.js file and alter the connection code with the string you copied above. Enter the username, password, cluster name, and database name for the defined variable.
Define variables for the username, password, cluster name, and database name as needed.
Add the below code which will basically use the connection string above to connect to the database and on success, will show the result.
We need to make use of a Router so we will use the below code to make it available for usage and then we will initialize the application to listen on port 3000.
Now, create a model.js file. We need to create a schema in the database to be able to add values as per the schema.
Add the below code to do so. We will first import the mongoose package and then define a schema with the required parameters and their corresponding types and whether they are required fields or not and the default value for the same. Then, we will export the schema for us to be able to use it.
We need to define routes for the creation and get requests. To do so, create a new file routes.js.
Import the following packages in the routes file.
Define a route for adding a new user to the list as shown in the image below making a post request and returning the result response.
Then, in the same file, define a route for fetching the created users using the get request thereby returning the result response.
Finally, export the route.
Now, run the server using the below command:
On success, you will see that the server will be started on the 3000 port.
On successful connection to the database, you will see the success message as shown in the image below after some time.
Now, to test the API, open the postman application. Select the method as POST.
Enter the request URL as ‘http://localhost:3000/add_user’ and then select the Body tab. Under that select the raw section and the type as JSON. Create an object in the request body with the user name and age as per our schema.
Once done, hit Send.
On successful creation, you will see the following message as shown in the image below with a randomly generated id for the same.
Now, let’s test the get API to get all the users. Change the request type to GET and hit the URL ‘http://localhost:3000/users‘ and click on Send.
On success, you will get the list of created users.
Now, follow the same creation process as shown above and create one more user, and then hit the get API URL again. You will see that the response now returns both the created users.
In this hands-on, we saw how we can connect to MongoDB using Mongoose and MongoDB Atlas in Node.js. We began with creating a new directory on the local machine. Initializing the app in the directory, we installed the required packages for the implementation.
Verifying the installation of the packages, we created a code file thereby putting in the code to connect to the database. Navigating to the MongoDB Atlas, we demonstrated how to sign up and create a new database.
We then configured a new user and added the IP so that we can access it in our code. Altering the parameters in our code, we then moved on to creating a model which is a database schema. Exporting the schema we then created route files with the API calls to add a record in the database and to list all the inserted records.
We then spun up the server and navigated to the postman application to hit the insert API. On successful execution, we ran the get API followed by testing out the same for multiple records. We will come up with more such use cases in our upcoming blogs.
If you are an aspiring MongoDB Developer and want to explore more about the above topics, here are a few of our blogs for your reference:
Stay tuned to get all the updates about our upcoming blogs on the cloud and the latest technologies.
Keep Exploring -> Keep Learning -> Keep Mastering
At Workfall, we strive to provide the best tech and pay opportunities to kickass coders around the world. If you’re looking to work with global clients, build cutting-edge products and make big bucks doing so, give it a shot at workfall.com/partner today!