DEV Community

Cover image for Using Mongoose to connect NodeJS and MongoDB
Aryan Dev Shourie
Aryan Dev Shourie

Posted on • Updated on

Using Mongoose to connect NodeJS and MongoDB

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

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

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/

website home

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

website sign

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

new project

Click on New Project

name project

Give a suitable name to your project.

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

mongo build

Create on Build Database.

mongo choose

Choose your required options, then click on Create.

mongo store

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

mongo network

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

Click on Connect

mongo driver

Choose the Drivers option.

mongo uri

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
Enter fullscreen mode Exit fullscreen mode

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));

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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`);
});
Enter fullscreen mode Exit fullscreen mode

To run the file, type the following command in your terminal -

node index.js
Enter fullscreen mode Exit fullscreen mode

You will see the following output -

Database Connected
Server started at Port 8080
Enter fullscreen mode Exit fullscreen mode

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

Connect with me on Linkedin :- Linkedin

Do check out my Github for amazing projects:- Github

View my Personal Portfolio :- Aryan's Portfolio

Top comments (4)

Collapse
 
navyaarora01 profile image
Navya Arora

Great Content!!

Collapse
 
aryan_shourie profile image
Aryan Dev Shourie

Thanks!!

Collapse
 
dali2g profile image
Mohamed Ali Mejdi

Great content for beginners !

Collapse
 
aryan_shourie profile image
Aryan Dev Shourie

Thanks!!