Now, let’s start with the code development for making MongoDB connection. We would be using the Mongoose library to handle the MongoDB connection and query interactions.

This MongoDB object modelling for Node.js library provides a schema-based solution for defining the model for our application data. It also offers in-built typecasting, validation, query building and business logic hooks along with more features.

Using this library will be making the developer’s life a little bit easy during the development as it abstracts the low-level MongoDB APIs and provides many user-friendly methods to handle the interaction with the MongoDB database.

1. Download Dependencies

As usual, we will start downloading and adding the Mongoose module as a dependent in the package.json file with the below command.

npm install mongoose --save

Also, the MongoDB module.

npm install mongodb --save

Once the two modules are downloaded into the node_modules directory, which is where the npm utility will download all the dependent modules from the www.npmjs.com and keep them locally for the application’s use, let’s continue with the adding more scripts in the mongodb.util.js file.

2. Load Required Modules/Files

Load the mongoose module with the below statement, by requiring it, just below the module.exports block.

var mongoose = require('mongoose');

Also, the MongoDB configuration needs to be loaded in this file so that we could get the mongodb connection details.

var mongodbConfig = require('../../config/mongodb/mongodb-config').mongodb;

3. Connect To MongoDB Database

Connection to the MongoDB can be made with the **mongoose.connect()**method. This method needs connection URI as a mandatory first parameter and options object as an optional second parameter. Also, it can accept a callback function as an optional parameter at the end.

mongodb.connect(uri, options, callbackFunction)

If we don’t pass the callback function while connecting, the connect method will return a promise, which we could handle in the calling function. Below will be the method for the promise return.

mongodb.connect(uri, options)

We will use the promise function so that we could add appropriate handling functions for success and failure of the promise.

4. Prepare Connection URI

As we have the MongoDB database details in the JSON configuration file, we will have prepared the connection URI as per the prescribed format to pass it to the mongoose.connect() function.

Below is the standard MongoDB connection URI format to connect to the MongoDB database.

mongodb://username:password@host:port/database?options

Let’s break this string to see what are the different components and their role in the below section.

  1. mongodb://: This is the required prefix which identifies that this is a string in the standard connection URI format.
  2. username:password@: This is an optional string. When specified, the client will be logging into the database with this credential after the connection to the MongoDB server is established. If this is not specified, the client will be logging into the database anonymously.
  3. host: This is the MongoDB server address, and it could be a hostname, IP address or UNIX domain socket.
  4. :port: The port number of the MongoDB database server and is optional.
  5. /database: The name of the database that we want to connect to in the MongoDB server, and this is also an optional parameter.
  6. ?options: Connection-specific options. We will use one or two of these options within this example.

The MongoDB connection details are in the JSON file, and we need to use that information to format the connection URI. So we will create a new function inside the mongodb.util.js of the MongoDB module for preparing the connection URI from the configuration JSON file.

function prepareConnectionString(config) {
    var connectionString = 'mongodb://';

    if (config.user) {
       connectionString += config.user + ':' + config.password + '@';
    }

    connectionString += config.server + '/' + config.database;

    return connectionString;
}

This function receives the input of the config object which contains the connection details and returns the connection URI as the response. Inside this function, connection URI is prepared as per the standard format as described in the above section. If the user and password are available in the config object, the credential is added to the connection string otherwise omitted.

5. Complete Init Function

Let’s continue with updating the init function with the database connection code. Now we know the mongoose method to connect to the MongoDB database and its inputs. We already have the function to prepare the connection URI from the config object, so lets complete the init function.

Inside the init function, let’s create two variables: one for options and another one for the connection string. Also, then call the mongoose.connect() function with those inputs and handle the promise functions for both success and failure.

function init() {
    var options = {
        promiseLibrary: require('bluebird'),
        useNewUrlParser: true
    };

    var connectionString = prepareConnectionString(mongodbConfig);

    mongoose.connect(connectionString, options)
        .then(function (result) {
            console.log("MongoDB connection successful. DB: " + connectionString);
        })
        .catch(function (error) {
            console.log(error.message);
            console.log("Error occurred while connecting to DB: : " + connectionString);
        });
}

For the options object, let’s add bluebird promise library that can be used by the mongoose module to throw the promises as required. So we need to add the bluebird module into the dependencies list with the below command.

npm install bluebird --save

To format the connection URI, we will use the new function prepareConnectionString() that we created a while back by passing the MongoDB config object we loaded at the beginning of this file.

Since we are using the mongoose.connect() without the callback function, means, using the promise version of it, we need to handle the promise. So, we pass a function to then function as input to handle the successful connection.

Also passed another function to the catch function to handle any connection failure. Inside each of those handler functions, we print the appropriate messages to the console for debugging purpose.

Even after these changes in the mongodb.util.js file, the test suites should still run without any failures.

As we have completed the whole MongoDB module with required functionality changes, let’s invoke the init function from the app.js to initialize the MongoDB connection during the application startup.

So let’s load the MongoDBUtil from the MongoDBModule in the apps.js, just below the initial load of all the app level dependent modules.

var MongoDBUtil = require('./modules/mongodb/mongodb.module').MongoDBUtil;

Just below the app.use() of all other modules in the apps.js, add the below line to invoke the init function for initializing the MongoDB connection.

MongoDBUtil.init();

This statement completes the MongoDB module. Restarting the application with *npm start *will make the database connection while the application is starting up. Either database connection success or failure message will be displayed at the console once the server is up and running.

MongoDB Connection — Success

You can check out the below link to the source code for this step in GitHub.

GitHub — Step 03 — MongoDB Module Setup> This blog post is an excerpt from the book Building Node.js REST API with TDD approach. Please check out the link for more information.

#mongodb #node-js

MongoDB Connection Initialization — Node.js API with TDD Tutorial
1 Likes18.00 GEEK