title: ReferenceError: db is not defined"
body: <p>I am trying to run some Js code from Java using the following code:</p>
  
  <pre><code>public void mapReduceScript()
      {
          try{
          MongoClient mongoClient = new MongoClient( CoreConfigModel.get("com.dice.api.mongo.host") , Integer.parseInt(CoreConfigModel.get("com.dice.api.mongo.port")));
          // Now connect to your databases
          DB db = mongoClient.getDB( "tracking" );
           System.out.println("Connect to database successfully");
          boolean auth = db.authenticate(CoreConfigModel.get("mongo.username"), CoreConfigModel.get("mongo.password").toCharArray() );
           System.out.println("Authentication: "+auth);
           ClassLoader classLoader = Thread.currentThread()
                      .getContextClassLoader();
           InputStream reduceStream = classLoader.getResourceAsStream("/data/mapReduceFunctionsByGroupIdIterative.js");
           String reduce = IOUtils.toString(reduceStream, "UTF-8");
           db.eval(reduce, new BasicDBObject("nolock", true));
          }
          catch (Exception e)
          {
              System.out.println(e);
          }
  
      }
  </code></pre>
  
  <p>and here are the contents of <code>mapReduceFunctionsByGroupIdIterative.js</code></p>
  
  <pre><code> function mapFunction() {
      if (!this.eventdata.Viewed || this.eventdata.Viewed.length === 0) {
          return;
      }
      var key = this.groupid;
      var value = {
          Dockey: this.eventdata.Viewed[0].Dockey,
          PID: this.eventdata.Viewed[0].PID,
          datecreated: this.datecreated,
      entityid: this.entityid
      };
      emit(key, value);
  }
  
  function reduceFunction(key, values) {
      function merge(target, firstSource) { 'use strict';
          if (target === undefined || target === null)
              throw new TypeError('Cannot convert first argument to object');
  
          var to = Object(target);
  
          var hasPendingException = false;
          var pendingException;
  
          for (var i = 1; i &lt; arguments.length; i++) {
              var nextSource = arguments[i];
              if (nextSource === undefined || nextSource === null)
                  continue;
  
              var keysArray = Object.keys(Object(nextSource));
              for (var nextIndex = 0, len = keysArray.length; nextIndex &lt; len; nextIndex++) {
                  var nextKey = keysArray[nextIndex];
                  try {
                      var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
                      if (desc !== undefined &amp;&amp; desc.enumerable)
                          to[nextKey] = nextSource[nextKey];
                  } catch (e) {
                      if (!hasPendingException) {
                          hasPendingException = true;
                      pendingException = e;
                  }
              }
          }
  
          if (hasPendingException)
              throw pendingException;
          }
          return to;
      }
  
      var mostRecentViews = {
          Dockey: {},
          PID: {}
      };
  
      values.forEach(function (value) {
          var key = value.Dockey ? 'Dockey' : 'PID';
          var reducedValue = {
              profileid: value[key],
              datecreated: value.datecreated,
          entityid: value.entityid
          };
          if (!(value[key] in this[key]) ||
                  new Date(value.datecreated) &gt; new Date(this[key][value[key]].datecreated)) {
              this[key][value[key]] = reducedValue;
          }
      }, mostRecentViews);
  
      var reducedObject = merge({}, mostRecentViews.Dockey, mostRecentViews.PID);
  
      return reducedObject;
  }
  
  function finalizeFunction(key, reducedValue) {
      var finalizedObject = Object.keys(reducedValue).map(function (key, index, array) {
          return reducedValue[key];
      });
  
      return finalizedObject;
  }
  
  var lastrundate = db.TRACKING_DATA.findOne({'_id': 'lastruntimeGroup'}).lastruntime;
  
  db.TRACKING_DATA.mapReduce(mapFunction,
                              reduceFunction,
                              {
                              out: { reduce: "LASTVIEWED_GROUP"},
                              query: { datecreated: 
                                              { $gt: lastrundate }
                                          },
                              finalize: finalizeFunction
                              }
                          )       
  
  db.TRACKING_DATA.update({'_id': 'lastruntimeGroup'},{'_id': 'lastruntimeGroup', 'lastruntime': new Date()},{upsert:true})
  </code></pre>
  
  <p>However when I excute the code I get thrown the error:</p>
  
  <pre><code>com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "errmsg" : "exception: ReferenceError: db is not defined" , "code" : 16722 , "ok" : 0.0}
  </code></pre>
  
  <p>I have two references to db one within my Java code which is defined:</p>
  
  <pre><code>DB db = mongoClient.getDB( "tracking" );
  </code></pre>
  
  <p>And one within my Js code which should be run in the mongo shell via:</p>
  
  <pre><code>db.eval(reduce, new BasicDBObject("nolock", true));
  </code></pre>
  
  <p>I have run the js file on the shell and it works as intended, so something either around my java code or call <code>db.eval()</code> is doing something funky.</p>