MongoDB is a NoSQL document oriented database program that uses JSON like document format. You can create your customised schemas in MongoDB. Here we will use Mongoose, a NPM package that provides a wide range of methods to use MongoDB in Express servers. Let’s see how we can connect MongoDB with ExpressJS server using Mongoose.

See How To Create A Simple ExpressJS Server.

Step -1:

First of all, we need to install Mongoose and Dotenv using the following command –

$ npm install mongoose dotenv

After successful installation we will add this modules to our index.server.js file and configure our Environment Variables. As we can’t add our credentials as a string because they are confidential. Using Dotenv, we can store our credentials in a different file named .env and use them anywhere in our project.

Step – 2:

Create a database in MongoDB. MongoDB provides a free tier that allows to use maximum 512 MB of storage. After creating a database, you will find a connect option. Click Connect and select the marked option.

Copy the below code –

Go back to your index.server.js file. Mongoose provides a method called connect() that returns a promise after initiating a connecting to the database. We will simply use then() and catch() keyword to handle the promise. Add DB_PASS variable in your .env file. Add connect() method according to the attached image –

 

After adding the code, restart your server. Bongo! Your application is now connected with MongoDB database. Now you can create your own Schemas and Models. We will see how to create schemas using Mongoose in our next post.

Leave a Reply

Your email address will not be published. Required fields are marked *