Karim Aya

Karim Aya


MongoDB Connection Initialization — Node.js API with TDD Tutorial

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.


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 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.


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

What is GEEK

Buddha Community

MongoDB Connection Initialization — Node.js API with TDD Tutorial

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers

Aria Barnes

Aria Barnes


Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.


Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application

Ray  Patel

Ray Patel


How to Validate and Geocode a Street Address in Java

When working with location services, it is important that the information you collect is accurate for your users or clients. Find out more!

When working with location services, it is important that the information you collect is accurate for your users or clients. This will prevent any mistakes in shipping, billing, and many other aspects of operations that rely on correct location information. For businesses that have applications using location services, this is especially important as any incorrect data can mean the displacement of goods or interrupted services.

The following APIs will allow you to fully validate street addresses by first parsing address data input and then verifying and normalizing the information. The last two APIs will also allow you to geocode and reverse geocode an address to receive more accurate location data for your applications.

#tutorial #api #address #java api #validation and verification #api access keys #api tutorial #validate #java api tutorials #api tutorials

Samanta  Moore

Samanta Moore


How to Validate an Email Address in Java

Email is one of the most universal tools for sharing and receiving information across the globe, with users able to connect with others online with almost no compatibility or access issues. Using this tool, information can be instantly and securely sent to partners on the other side of the world, and personal information can be verified without divulging sensitive data about a user.

Along with this widespread use, however, comes key security measures that must take place in order to ensure the safety of your organization and data. This is particularly the case when receiving email information from previously unknown sources. These risks can include phishing attempts, malware, and other threats that can cause a negative impact to your business. Furthermore, when receiving an email address via account forms and user sign up information, you need to check that the information you are given is not only correct and real, but also that it does not lead to any malicious sources that could harm your organizational security.

The following APIs will allow you to instantly verify and validate an input email address without sending any kind of notification to the email user. This will help protect your organization in the event of any threats. The goal of this tutorial is to provide you with the tools to protect your organization’s information while providing a way to verify new accounts and user information.

This will be done through three separate functions. The first will analyze the validity of an email address’ syntax. The second will check for the address’ servers, and the third performs a full email address validation including returning the results for the previous two functions.

#java #api #java api #api access keys #api tutorial #email verification #email validation #java api tutorials #java apis #api tutorials