Using Mongoose to connect NodeJS and MongoDB
Tags: webdev, node, mongodb, mongoose
Published: 2023-06-09 18:22:01


**Node.js** is an open-source, cross-platform JavaScript runtime environment and library for running web applications outside the client's browser.

**MongoDB** is a document database used to build highly available and scalable internet applications. It is a **non-relational** database that provides support for JSON-like storage.

**Mongoose** is a Node.js based **Object Data Modelling (ODM)** library for MongoDB. It manages relationships between data and provides Schema validation.

**A typical MongoDB document looks like this -**

![mongodoc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/12xzqa6lbhw5mj0kiowi.PNG)

## Why is MongoDB used with Node.js?
The **MongoDB + Node.js driver** makes using MongoDB with Node.js a seamless and smooth experience. The driver automatically maps JavaScript objects to **BSON** documents, meaning that the developers can easily work with their data.

![node+mongo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qhxlq30nlswaotz6w8j1.png)

Thus, if we want to have MongoDB as the database of our Application in which we are using Node.js, it is advisable to use Mongoose, as Mongoose basically **establishes a connection** between Node.js and MongoDB.

## Steps to Connect Node.js and MongoDB using Mongoose

**Step 1 :** Firstly, you need to create an account on the **official MongoDB website**. You can visit it here - [https://www.mongodb.com/](https://www.mongodb.com/)

![website home](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bzr5eei8py51nsbmqazl.PNG)

You can either sign up using your Gmail account or your Github account.

![website sign](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmejmdckvgni03vvefq1.PNG)

**Step 2 :** After creating an account, now you have to create a new **Project**.

![new project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hyivg1ton9odvfz74d4v.PNG)

Click on **New Project**

![name project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p8fnymstu20fvcva1mid.PNG)

Give a suitable name to your project.

**Step 3 :** Now, after creating a Project, you have to create a **new Database.**

![mongo build](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fhfh0slzpuj4gvpu3a75.PNG)

Create on **Build Database.**


![mongo choose](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ljhlng6yqgx46zy8m61.PNG)

Choose your required options, then click on **Create**.


![mongo store](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/le0ayxmesf2cjzvymdid.PNG)

Now, store your **username** and **password** in a safe location, as it will be required later.


![mongo network](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ncwa1tqfmnaqhq2wfwux.PNG)

Now, set up the I.P. Address for your project. Click on **Add My Current IP Address**

Finally, click on **Finish and Close**.

You have successfully created a **new Project** and a **new Database**.

**Step 4 :** Now, you have to connect your Node.js project to MongoDB Atlas using **Mongoose**.


![Mongo Connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wclks5zphri8dh1mosvz.PNG)

Click on **Connect**


![mongo driver](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9p3sqavbhcp8zty3ysr.PNG)

Choose the **Drivers** option.


![mongo uri](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xmpa7bcj1a81x7skyb52.PNG)

Copy and store your MongoDB URI, as you will need it later.
Click on **Close**.

Now, install Mongoose in your project with the following command - 

```
npm install mongoose
```
Create a file named **conn.js**, write the following code in it -

```
const mongoose = require("mongoose");

const DB = mongodb+srv://username:<password>@cluster0.j3sj2kd.mongodb.net/?retryWrites=true&w=majority;

mongoose.set("strictQuery" , true);

mongoose.connect(DB, {
    useNewUrlParser : true,
    useUnifiedTopology : true
}).then(()=>{
    console.log("Database Connected");
}).catch((err)=> console.log(err));

```
Replace the **password** with your Database Password in your MongoDB URI.

Now, we also want to create a Server, for which we will install the **ExpressJS** module. We can install it with the following command -

```
npm install express
```

Create another file **index.js**, write the following code in it -

```
const express = require("express");

require("./conn");

const app = express();

app.listen(8080, () => {
    console.log(`Server started at Port 8080`);
});
```
To run the file, type the following command in your terminal -

```
node index.js
```
You will see the following output -

```
Database Connected
Server started at Port 8080
```

And thats it! You have successfully learnt how to connect NodeJS with MongoDB by using Mongoose!

Connect with me on Linkedin :- [Linkedin](https://www.linkedin.com/in/aryandev-shourie-175025229/)

Do check out my Github for amazing projects:- [Github](https://github.com/Aryan2727-debug)

View my Personal Portfolio :- [Aryan's Portfolio](https://personal-portfolio-aryan.netlify.app/)