How to NodeJS- Node js MongoDB Express

In this guide, we are going to learn how to query and insert data and so forth using Node.js, MongoDB, and Webstorm IDE with Express. If you have no idea what is Node.js is or you don’t know how to install it or how to install Express or Webstorm or MongoDB, Read the following guides before continue.

How to NodeJS- Installing Node JS
How to NodeJS- Run First Node.Js Web Server
How to NodeJS- Express app directory structure
How to MongoDB- Installing MongoDB

Once you finished with installations, open up Webstorm IDE and create a Node.js Express App project. Here, we created “first-project”. it will generate many files for you.

 

Add and configure MongoDB plugin

Let’s go ahead and configure MongoDB plugin on Webstorm IDE. First of all, we have to download the mangoDB plugin. In order to download the plugin, go to File menu > settings or use short key Ctrl+Alt+s to access settings.  Navigate plugin tab from settings and click on browse repositories. Search for Mongo plugin and select Mongo plugin and install. Once the installation is finished, it will ask for restart IDE in order to save the changes.

 

Node js MongoDB Express

 

Once you restart the Webstorm IDE, we can configure the MongoDB plugin. In order to configure MongoDB, you have to use Mongo Explorer. Enable the Mongo Explorer in View > Tools window.

On Mongo Explorer, add MongoDB configuration by clicking the button add configuration which will direct you to Mongo servers in the settings tab.

 

Node js MongoDB Express

 

Add your Path to Mongo Shell. If you’re installed MongoDB in the default location, the path will be C:\Program Files\MongoDB\Server\3.4\bin\mongo.exe. Apply the changes once you’ve set the path properly.

To add Mongo server to our project, click on small plus button.

 

Node js MongoDB Express

 

Enter a label name and leave other settings default. Click on OK and Apply the changes.

 

Node js MongoDB Express

 

Connect to MongoDB using Mongo Explorer

In order to connect the MongoDB, start the MongoDB service using the command prompt. Let’s go ahead and open up command prompt and change directory to Mongo bin folder and run mongod.exe.

    C:\Program Files\MongoDB\Server\3.4\bin>mongod.exe

 

It will start the Mongo service through the default port. Once we started the service, we can connect to Mongo server from Mongo Explorer window from Webstorm IDE. You can also use Mongo shell to run MongoDB commands from the WebstormIDE.

 

Install Mongo module

Install the MongoDB driver and its dependencies by executing the following npm command. Launch the embedded Terminal by hovering your mouse pointer over the small icon in the lower left corner of WebStorm and choosing Terminal from the menu and executing the following npm command.

Install MongoDB
    npm install mongodb --save

This will download the MongoDB driver and add a dependency entry in your package.json file. Let’s go ahead and use MongoDB to our node.js application. Add the following code to “app.js” file. It will create a connection to MongoDB database.

    var mongo = require('mongodb');

 

Render MongoDB Data to a Webpage

Consider that we have contact database on MongoDB and have the following data.

Node js MongoDB Express

 

Let’s create a new route in index.js to render the page named “contactList” with data from Mongo database. We will add request to render all the information currently in MongoDB collection ‘contactlist’ and it will display on the page. To do that, add the following route code to “index.js” file.

index.js
   var mongodb = require('mongodb');

   router.get('/contactlist', function(req, res){

       // Get a Mongo client to work with the Mongo server  
       var MClient = mongodb.MongoClient;
       // Define where the MongoDB server is
       var url = 'mongodb://localhost:27017/contacts';
       // Connect to the server
       MClient.connect(url, function(err, db) {
          if (err) {
               console.log('Unable to connect to the Server', err);
          } else {
               console.log('Connection established to', url);
               // Get the documents collection 'contacts'
               var collection = db.collection('contactList');

               // Find all contacts
               collection.find({}).toArray(function (err, result) {
                  if (err) {
                       res.send(err);
                  } else if (result.length) {
                      res.render('contactList',{
                            // Pass the result to contactList.jade page
                            "ContactList" : result
                      });
                  } else {
                     res.send('No documents found');
                  }

                  //Close connection
                  db.close();
                  });
           }
       });
   });

 

The above code will connect the MongoDB database “contacts” and retrieve all data from the “contactList” collection. Once the database is connected and all data found, it will render the contact data in “contactList.jade” file. Let’s create contactList.jade file.

Create a new jade file named “contactList.jade” inside view folder and add the following code to it. to learn more about Jade templating, refer the guide Jade Templating Engine.

contactList.jade
    extends layout

    Block content
       h2 Contacts List
       ul 
          each contact in contactList
          li 
             b #{contact.firstname} #{contact.lastname} 
             span  
             span #{contact.email}

 

The above each statement will output all contact records from the contacts database. Let’s see the result.

To see the result on the browser, Rerun our Node project and open localhost:3000/contactList on the browser. You will see all the contacts rendered from the database.

Node js MongoDB Express

 

Add data to the Mongo Database

In this section, we will learn to add new contact record to our contactList collection on Mongo database through Node.js Express application. To add new data to the database, we need a form page in our application and we have to post it by post action to a specified post route. The route method will add the new data posted through the form to our Mongo database.

Firstly, add the following routes  “index.js” file.

// Route to the page we can add contact record from newcontact.jade
router.get('/newcontact', function(req, res){
    res.render('newcontact', {title: 'Add Contact' });
});

The above code will route to “newcontact” form where we can add contact records.

 

Create a new jade file named newcontact.jade inside view folder and add the following jade code to it to render newcontact” form.

newcontact.jade
   extends layout

   block content
      h3= title
      form#form_add_contact(name="addcontact", method="post", action="/addcontact")
        span First Name
        span  
        input#input_firstname(type="text", placeholder="firstname", name="firstname")
        br
        br
        span Last Name
        span  
        input#input_lastname(type="text", placeholder="lastname", name="lastname")
        br
        br
        span Email Address
        span  
        input#input_email(type="text", placeholder="email", name="email")
        br
        br
        button#submit_contact(type="submit") submit

 

The following route will receive the post request from “newcontact.jade” and insert the contact data to our database.

Route to newcontact.jade
   router.post('/addcontact', function(req, res){
 
    
       var MongoClient = mongodb.MongoClient;
 
       var url = 'mongodb://localhost:27017/contacts';
 
       // Connect to the server
       MongoClient.connect(url, function(err, db){
         if (err) {
           console.log('Unable to connect to the Server:', err);
         } else {
           console.log('Connected to Server');
 
           // Get the documents collection
           var collection = db.collection('contactList');
 
           // Get the contact data recived from the form
           var contact1 = {firstname: req.body.firstname, 
                  lastname: req.body.lastname, 
                  email: req.body.email,};
 
           // Insert the contact record into the Mongo database
           collection.insert([contact1], function (err, result){
             if (err) {
               console.log(err);
             } else {
 
               // Redirect to the updated contactList
               res.redirect("contactList");
             }
  
             // Close the database
             db.close();
           });
 
         }
       });
 
    });

 

To add a new contact, Rerun our Node project and open “http://localhost:3000/newcontact” on the browser. Fill out the form with contact details first name, last name, and email address and submit.

Node js MongoDB Express

 

Once you submit the form, new contact record will be added to the contactList and the form redirects to updated contactList.

Node js MongoDB Express

 

 

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...