Connect to MongoDB in Express Project — Part 2
Tags: Mongodb Database, Expressjs And Mongodb, Mongoose Apollo Server, Database Connection, Mongodb

We are going to connect MongoDB in express project. We will also see, how we can read environment variables also.

Create expressjs project

We have already created a expressjs project. We are going to use same project for further steps. If you don’t have, you can go through below link.

Create GraphQL API in Expressjs Project Using Apollo Server Express

Install MongoDB in your system

We assume that you have already installed MongoDB in your system. If you have not installed then you can download from below link and install:

https://www.mongodb.com/try/download/community?tck=docs_server

Store config in the environment Variables

What is environment variables?

Environment variables allow us to manage the configuration of our applications separate from our codebase. Wherever our app needs configuration, we use environment variables. Separating configurations make it easier for our application to be deployed in different environments.

Here are some specific examples of common scenarios when you should use environment variables.

Which HTTP port to listen on. Port will be different for staging, local, production environment Database details will be different for development, staging, test, or production server Location of static files etc…

For reading environment variables we can use dotenv library. Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. we can install dotenv by using npm.

Install

npm install dotenv

Usage:

As early as possible in your application, require and configure dotenv.

require(‘dotenv’).config()

Let us Install dotenv module in the express project

Open command prompt and go to project folder and install.

F:

cd F:\javascript-projects\express-projects\gqlapi

npm install dotenv --save

We can view dotenv library in package.json file.

Create .env file in project root folder

Open project in any your favorite editor and create .env file in the root directory of your project.

Declare PORT in .env file

PORT=4000

Read .env file

Include dotenv in src/index.js file

require('dotenv').config()

Read PORT value from .env file

const port = process.env.PORT

console.log({port})

Run the project

npm run dev

We can see we are able to read environment variables from .env file.

Install Mongoose library

Mongoose is the Object Document Mapper (ODM) library for Node.js and it is written on the top of the Node.js native MongoDB driver. It is used to establish a connection with the MongoDB database.

Stop the server by pressing Ctrl + c and run below command.

npm install mongoose --save

Let us add database details to .env file

In this example we are using mongodb. We need to add database details in .env file.

MONGO_HOSTNAME=127.0.0.1

MONGO_PORT=27017

MONGO_DB=library

Create db.js for MongoDB connection

When you are connecting to MongoDB, make sure MongoDB sevice must be running.

Create db.js file inside src folder. Write below code in db.js file.

Below are some of the options that are important for tuning Mongoose.

useNewUrlParser — The underlying MongoDB driver has deprecated their current connection string parser. Because this is a major change, they added the useNewUrlParser flag to allow users to fall back to the old parser if they find a bug in the new parser. You should set useNewUrlParser: true unless that prevents you from connecting. Note that if you specify useNewUrlParser: true, you must specify a port in your connection string, like mongodb://localhost:27017/dbname. The new url parser does not support connection strings that do not have a port, like mongodb://localhost/dbname.

useFindAndModify — True by default. Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().

useCreateIndex — False by default. Set to true to make Mongoose’s default index build use createIndex() instead of ensureIndex() to avoid deprecation warnings from the MongoDB driver.

useUnifiedTopology — False by default. Set to true to opt in to using the MongoDB driver’s new connection management engine. You should set this option to true, except for the unlikely case that it prevents you from maintaining a stable connection.

//file: src/db.js //Include mongoose library

mongoose = require('mongoose'); module.exports = {

connect: DB_URL => {



mongoose.set('useNewUrlParser', true);

mongoose.set('useFindAndModify', false);

mongoose.set('useCreateIndex', true);

mongoose.set('useUnifiedTopology', true);

mongoose.connect(DB_URL);



//Log an error if we fail to connect

mongoose.connection.on('error', err => {

console.error(err);

console.log(

'MongoDB connection failed: ' + DB_URL

);



process.exit();



});

},



//close the connection

close: () => {

mongoose.connection.close();

}

};

Connect to MongoDB

Include db.js file in src/index.js

//file: src/index.js

const db = require('./db');

Read database details from .env file and connect to database

//file: src/index.js

// Connect to the database

const MONGO_HOSTNAME = process.env.MONGO_HOSTNAME;

const MONGO_PORT = process.env.MONGO_PORT;

const MONGO_DB = process.env.MONGO_DB; const DB_URL = `mongodb://${MONGO_HOSTNAME}:${MONGO_PORT}/${MONGO_DB}` db.connect(DB_URL);

Run the server

npm run dev

We can see there is no error it is connected to MongoDB.