CSCI 421 - Lecture 4

Instructor's Class Notes

  1. Part 2:5 - Building a Data Model with MongoDB and Mongoose
  2.  

  3. Adding Mongoose to your Application - Following are the steps involved:
    1. Installing Mongoose - While in your application directory, execute the following:
      
      > npm install --save mongoose
                      
      The above command should update the dependencies of the package.json file, as shown in the excerpt below:
      
      "dependencies": { 
          "express": "~4.9.0",
          "body-parser": "~1.8.1",
          "cookie-parser": "~1.3.3", 
          "morgan": "~1.3.0", 
          "serve-favicon": "~2.1.3", 
          "debug": "~2.0.0",
          "jade": "~1.6.0",
          "mongoose": "~3.8.20"
      }
    2. Adding a Mongoose Connection to your Application - Following are the steps involved:
      1. Setting Up the Connection File - Create a file, db.js, and place it in the app_server/models directory. For now, this file will only have the following command:
        
        var mongoose = require('mongoose');                    
                            
      2. Adding database to app.js - Near the top of the app.js file add a requires statement to load db.js as so (see new statement in bold):
        
        var express = require('express');
        var path = require('path');
        var favicon = require('serve-favicon');
        var logger = require('morgan');
        var cookieParser = require('cookie-parser');
        var bodyParser = require('body-parser');
        require('./app_server/models/db');                    
                            
      3. Creating the Mongoose Connection - Update db.js with a URI and a connect method call:
        • URI Syntax - The Uniform Resource Locator (URI) syntax for a MongoDB is as follows:

        • db.js Updates - Add the following (or similar depending on DB name) to your db.js file:
          
          var dbURI = 'mongodb://localhost/blogger';
          mongoose.connect(dbURI);                        
                                  
          Note: - The first time your application successfully connects to the database the database will be created, if needed.
        • Monitoring the Mongoose Connection - You can add additional code to the bottom of db.js in order for your app to write to the console when connection events happen:
          
          // Monitor and report when database is connected                      
          mongoose.connection.on('connected', function () {
            console.log('Mongoose connected to ' + dbURI);
          });
          
          // Monitor and report error connecting to database
          mongoose.connection.on('error',function (err) {
            console.log('Mongoose connection error: ' + err);
          });
          
          // Monitor and report when database is disconnected
          mongoose.connection.on('disconnected', function () {
            console.log('Mongoose disconnected');
          });                        
                                  
        • Graceful Shutdown and DB Disconnect - You will need extra code in db.js in order for your application to gracefully shutdown and disconnect from the database when its process terminates. Add the following to the bottom:
          
          // Closes (disconnects) from Mongoose DB upon shutdown                       
          gracefulShutdown = function (msg, callback) {
            mongoose.connection.close(function () {
              console.log('Mongoose disconnected through ' + msg);
              callback();
            });
          };
          
          // For nodemon restarts
          process.once('SIGUSR2', function () {
            gracefulShutdown('nodemon restart', function () {
              process.kill(process.pid, 'SIGUSR2');
          }); });
          
          // For app termination
          process.on('SIGINT', function() {
            gracefulShutdown('app termination', function () {
              process.exit(0);
          }); });
          
          // For Heroku app termination
          process.on('SIGTERM', function() {
            gracefulShutdown('Heroku app shutdown', function () {
              process.exit(0);
          }); });                        
                                  
        • A Complete db.js File - Here is the complete file:
          
          var mongoose = require( 'mongoose' );
          var gracefulShutdown;
          var dbURI = 'mongodb://localhost/myapp';
          mongoose.connect(dbURI);
          
          // Monitor and report when database is connected                      
          mongoose.connection.on('connected', function () {
            console.log('Mongoose connected to ' + dbURI);
          });
          
          // Monitor and report error connecting to database
          mongoose.connection.on('error',function (err) {
            console.log('Mongoose connection error: ' + err);
          });
          
          // Monitor and report when database is disconnected
          mongoose.connection.on('disconnected', function () {
            console.log('Mongoose disconnected');
          }); 
          // Closes (disconnects) from Mongoose DB upon shutdown    
          gracefulShutdown = function (msg, callback) {
            mongoose.connection.close(function () {
              console.log('Mongoose disconnected through ' + msg);
              callback();
            });
          };
          
          // For nodemon restarts
          process.once('SIGUSR2', function () {
            gracefulShutdown('nodemon restart', function () {
              process.kill(process.pid, 'SIGUSR2');
          }); });
          
          // For app termination
          process.on('SIGINT', function() {
            gracefulShutdown('app termination', function () {
              process.exit(0);
          }); });
          
          // For Heroku app termination
          process.on('SIGTERM', function() {
            gracefulShutdown('Heroku app shutdown', function () {
              process.exit(0);
          }); });

     

  4. What's Inside a MonogoDB Database?
  5.  

  6. Defining Schema for Data Model using Mongoose
  7.  

  8. Adding Models to your Database
  9.  

  10. Static Data via Controllers