CS6320:  SW Engineering of Web Based Systems

 

Simple NodeJS run on server directly (not invoked through web) to execute some simple database operations on a MongoDB.

 

assumes you have previously created a mLab MongoDB account (look here on how to do through Heroku addon)

 

 

STEP 1: copy code into file nodeJSMongoDBTest.js

  • This assumes you have already created a project either locally or on Heroku and in the main application directory create the nodeJSMongoDBTest file

  • CODE: 1) creates by insertion a new Collection called songs if it did not already exists 2) then adds 3 entries.
  • /*
    * Taken from  http://docs.mongodb.org/ecosystem/drivers/node-js/
     * A Node script  connecting to a MongoDB database given a MongoDB Connection 
    URI.
    */
     
    var mongodb = require('mongodb');
     
    // Create seed data -- it is in JSON format
    var seedData = [
      {
        decade: '1970s',
        artist: 'Debby Boone',
        song: 'You Light Up My Life',
        weeksAtOne: 10
      },
      {
        decade: '1980s',
        artist: 'Olivia Newton-John',
        song: 'Physical',
        weeksAtOne: 10
      },
      {
        decade: '1990s',     artist: 'Mariah Carey',     song: 'One Sweet Day',
        weeksAtOne: 16
      } ];
     
    // Standard URI format:  mongodb://[dbuser:dbpassword@]host:port/dbname
    // GO TO mLab.com account to see what YOUR database URL is
    //CHANGE the url so it is correct for your account var uri ='mongodb://YOUR_LOGIN:YOURPASSWROD@WHATEVER.mlab.com:xxxxx/dnName';
     
    //using mongodb module
    mongodb.MongoClient.connect(uri, function(err, db) {
      
      if(err) throw err;
     
      /*
       * First we'll add a few songs. Nothing is required to create the
       * songs collection; it is created automatically when we insert.    */
      var songs =  db.collection('songs');
     
       // Note that the  insert method can take either an array or a dict.
      songs.insert(seedData, function(err, result) {  
        if(err) throw err;
    
        /*
         * Then we need to give Boyz II Men credit for their contribution
         * to the hit "One Sweet Day".
         */     songs.update(       { song: 'One Sweet Day' },       { $set: { artist: 'Mariah Carey ft. Boyz II Men' } },       function (err, result) {       
            if(err) throw  err;                  
            /*
             * Finally we  run a query which returns all the hits that spend 10 or
             * more weeks  at number 1.
             */                
            songs.find({ weeksAtOne : { $gte: 10 } }).sort({ decade: 1}).toArray(function (err, docs) {
              if(err)  throw err;
    
              docs.forEach(function  (doc) {
                 console.log('In the  ' + doc['decade'] + ', ' + doc['song'] + ' by ' + doc ['artist'] + ' topped  the charts for ' + doc['weeksAtOne'] + ' straight weeks.');
             });
             
              // uncomment the following code if you wish to drop the collection (like a table) songs
    /***************************commented OUT
               songs.drop(function (err) {
                  if(err)  throw err;          
                  // Only  close the connection when your app is terminating.
               db.close(function (err) {
                   if(err) throw err;
                });
                });
    */
    
    
             
            });
          }
        );
      });
    });

STEP 2: add mongodb module to the application (if you have not already) and add to the dependencies

Now install mongodb module in the myapp directory and save it in the dependencies list. For example:

$ npm install mongodb --save  

 

STEP 3: run your new code and see the results in the mLab.com console

Run the app with the following command:

$ node nodeJSMongoDBTest.js  

 

 

 

question: What will happen if you rerun the code? try it out.

 

 

Understanding some of the code -see CRUD (create, read, update, delete) in action

mongodb.MongoClient.connect(uri, function(err, db) connect to specified uri and execute function upon connection
var seedData = [
 {
 decade: '1970s',
 artist: 'Debby Boone',
 song: 'You Light Up My Life',
 weeksAtOne: 10
 },
 {
 decade: '1980s',
 artist: 'Olivia Newton-John',
 song: 'Physical',
 weeksAtOne: 10
 },
 {
 decade: '1990s',
 artist: 'Mariah Carey',
 song: 'One Sweet Day',
 weeksAtOne: 16
 }
 ];

This is the JSON object representing 3 entries in our songs collection we want to enter.

 

 

NOTE: we have 4 idices (like columns) in our songs collection (like a databasetable) and they are:

  • decade
  • artist
  • song
  • weeksAtOne

 

songs.insert(seedData, function(err, result)

try to insert new entries into the songs collection first creating the collection if it does not already exist

the entries are represented by the json object "seedData"

execute the function upon callback (being done)

songs.update(
{ song: 'One Sweet Day' },
{ $set: { artist: 'Mariah Carey ft. Boyz II Men' } },
function (err, result)

update entry with song='One Sweet Day' to change the artist to ='Mariah Carey ft. Boyz II Men'

when done call the call back funciton specified

songs.find({ weeksAtOne : { $gte: 10 } }).sort({ decade: 1 }).toArray(function (err, docs) {

this is like a select (read) statment where weeksAtOne>10 and sorting by decade in asscending order (that is the :1) and then get results as an array that is passed to the call back function
function (err, docs) {
  
if(err) throw err;
 docs.forEach(function (doc) {
   console.log('In the ' + doc['decade'] + ', ' + doc['song'] + ' by ' +
doc['artist'] + ' topped the charts for ' + doc['weeksAtOne'] +
' straight weeks.'); });

This cycles through the docs[] array representing the retrieved entries from the songs collection.

 

Note you access items by indexing the array docs[] with a column value called an index in mongoDB collection

 

 

Direct Access form user Application or Go through an API ??????

 

while more work creating an API initially, it means that you DONT DUPLICATE the work from your different interfaces like a web (Angular), different server application (e.g. NodeJS) or a mobile App (e.g. iOS).

 

What does it mean to create an API --- you create a series of spearate applications (like in NodeJS with Express) that serve up results of desired CRUD operations on your Database that are accessed via WEB URLs ---example

 

© Lynne Grewe