Professional Application Development in MEAN Stack - Part 5
Date Published: 06/23/2018
In this part, we will create MongoDB database, the contact us page model in server side (Node.js), save the user message information into the database and send an email to website admin with user message and contact information. This would be a start of our journey to actually create the dynamic website.

Download Source on GitHub

Introduction

So in previous part, we developed node.js server side code to send the user message through an email to admin. In this part, we will also save this message in the database. We will create the MongoDB database and Contact model class to hold the message attributes along validation rules. 

Let's Start

    1. First thing, let's install the mongoose, a famous Object Data Modeling (Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in typecasting, validation, query building, business logic hooks and more, out of the box.)
    2. Drag the bottom blue ribbon and go to TERMINAL tab (or select menu view -> Integrated Terminal). Ente the command cd server to go to server project. After that, enter the command npm i mongoose --save.
    3. Give some time to mongoose package installation and wait for a successful message.
    4. If you have don't have previous part's code, you can download or clone it from here. Once the code is downloaded, make sure it is comipleable and running fine before moving to next step.
    5. Next, we will update the Contact model that will contain all properties i.e. Name, Phone, Email Address and Message and their validation rules.
    6. Edit the models -> contactModel.js and replace its content with the following: 
      const mongoose = require('mongoose');
      const emailer = require('../shared/email');
      // Contact Schema
      
      const ContactSchema = mongoose.Schema({
        Name: {
          type: String,
          required: true
        },
        Phone: {
          type: String,
          required: true
        },
        EmailAddress: {
          type: String,
          required: true
        },
        Message: {
          type: String,
          required: true
        }
      });
      
      const Contact = module.exports = mongoose.model('Contact', ContactSchema);
      
      
      module.exports.sendContactEmail = function (name, email, message, callback) {
        let msgplain = name + ' has sent you a message ' + email + '-' + message;
        let msghtml = name + ' has sent you a message <br>' + 'Email Address: ' + email + '<br><br>Message: ' + message;
        emailer.sendEmail(process.env.FROM_EMAIL, '', 'New Message Received from Mazhar & Co.', msgplain, msghtml, callback);
      }
    7. So the email code snippet is same as previous part, the update is the ContactSchema that is a model we are creating through mongoose library. You can see we are specifying the data type and validation rule i.e. all fields are required. 
    8. Since we updated the Contact model class, let's update the route to save the Contact information into the database where previously it was only sending an email to admin.
    9. Edit the routes -> contact.js file and replace its content with follows:  
      const express = require('express');
      const router = express.Router();
      const config = require('../config/database');
      const Contact = require('../models/contactMdl');
      
      router.post('/contact', function (req, res) {
          let cntctObj = new Contact(req.body);
          cntctObj.DateAdded = new Date();
          cntctObj.DateUpdated = new Date();
          cntctObj.save(function (err) {
            if (err) {
              res.json({ success: false, msg: "There is some error in sending message!" });
              return;
            } else {
              Contact.sendContactEmail(req.body.Name, req.body.EmailAddress, req.body.Message,
                function (error, info) {
                  if (error) {
                    res.json({ success: false, msg: error });
                  } else {
                    res.json({ success: true, msg: "Thank you for contacting, we will get to you back soon!" });
                  }
                }
              );
            }
          });
        });
      
      module.exports = router;
      


  1. In above code snippet, we created the HTTP Post request with the path as contact, next parameter is a callback function where we are saving the contact information in the database and in database save's callback method, we are sending an email to the admin. 
  2. In Contact save method, we are creating a Contact object and assigning the value from request object that is being sent from the client side and then calling the save method from mongoose model schema. Remember, we are creating mongoose model in a contactMdl.js file and exporting it as a module. Here, in the fourth line from top, we are adding the reference of contactMdl
  3. The next step is to install MongoDB, help yourself to download and install the appropriate version from here.
  4. I am quite lazy so I like GUI for MongoDB, you can use anyone but I would go for Robo 3T (formel Robomongo), download and install it from here. It's quite self-explanatory. Run the Robo 3T, go to File -> Connect, select Create a link from the opening window and follow the instructions. Create the reasonable connection name e.g. fullstackhub. Once the connection is created, you are all set, by default the connection listens on 27017 that can be updated too, but for now, let's keep the default one. 
  5. Cool, next let's create a database connection in our node.js server application, create a new folder config in the server folder. In config folder, create a database.js file and add the following code in it:  
    module.exports = {
        database:'mongodb://127.0.0.1:27017/mazharncoweb'
      }
  6. Once we will create the database connection in the application and run it the first time, it will automatically create a mazharncoweb database, you can keep whatever name you are comfortable with. 
  7. Next step is to add the newly created database.js file reference in our starter file mazharnco.js and connect to the MongoDB through the above-given connection string.
  8. Edit the mazharnco.js file in root server folder and update it as follows:  
    const express = require('express');
    const path = require('path');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    const contacts = require('./routes/contact');
    const mongoose = require('mongoose');    //Added mongoose reference.
    const config = require('./config/database'); //Added database connection string's file reference
    
    //Connecting to MongoDB 
    mongoose.connect(config.database, function (err) {
        if (err) {
            console.log('Not connected to the database: ' + err);
        } else {
            console.log('Successfully connected to MongoDB');
        }
    });
    
    var app = express();
    
    app.engine('html', require('ejs').renderFile);
    app.use(express.static(path.join(__dirname, './views')));
    
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(cors());
    app.use("/api", contacts);
    
    app.get('*', function (req, res) {
        res.render(path.join(__dirname, './views/index.html')); // load our public/index.html file
    });
    
    const port =  process.env.PORT;
    
    app.listen(port, function () {
        console.log('Server started on port ' + port);
    });
  9. So in above file, we added mongoose library and newly created database config file reference. next, we are using mongoose connect method to connect to MongoDB by specifying config.database variable from config file i.e. mongodb://127.0.0.1:27017/mazharncoweb.
  10. In app.use("/api", contacts); statement, we are appending api with contact route. So the final contact Post request would be http://localhost:3000/api/contact
  11. Before running the application, make sure you provided Admin email and password in environment.json file in server folder: 
    {
        "apps": [
            {
                "name": "mazharnco",
                "script": "./mazharnco.js",
                "watch": true,
                "env": {
                    "NODE_ENV": "development",
                    "ADMIN_EMAIL":"YOUR EMAIL ADDRESS HERE",
                    "ADMIN_EMAIL_PW":"YOUR EMAIL's PASSWORD HERE",
                    "EMAIL_SERVICE":"Gmail",
                    "FROM_EMAIL":"XXXXXXX@yahoo.com",
                    "PORT":"3000"
                },
                "env_production": {
                    "NODE_ENV": "production",
                    "ADMIN_EMAIL":"YOUR EMAIL ADDRESS HERE",
                    "ADMIN_EMAIL_PW":"YOUR EMAIL's PASSWORD HERE",
                    "EMAIL_SERVICE":"Gmail",
                    "FROM_EMAIL":"XXXXXXX@yahoo.com",
                    "PORT":"5001"
                }
            }
        ]
    }
  12. That's pretty much it for this part, now, right click on server folder and select option Open in Terminal. In Terminal window run the commandpm2 start environment.json --env development.
  13. Right click on mazharncoweb folder and select option Open in Terminal. In Terminal window run the command: ng serve -o
  14. Wait until web application is opened in your default browser, go to Contact Us page, fill all information in the contact form and hit the Send Message button. You should receive a successful message after few moments. Go to Robo 3T client, a new database should be created with the name mazharncoweb, right click on it and select option Refresh. Go to Collections, you would see the only contact collection with your newly created contact record. 
  15. Feel free to test API http://localhost:3000/api/contact in Postman (make sure your server node.js application is up and running):  
  16. Let me know if you have any issue and suggestion for improvement. We will keep moving forward to create admin section where we can dynamically create menu items, pages, read the messages etc.



Keywords: Angular Reactive Form tutorial, Node.js nodeemailer, MEAN stack tutorial, Angular 5 tutorial for beginners, MEAN Stack tutorial for beginners, Rxjs tutorial or beginner, Rxjs vs Promise,nodemailer,pm2, Node.js MongoDB, Node.js mongoose configuration