title: MongoDB. Map-Reduce finalize function
body: <p>I want to calculate users with accumulating by dates. I have the following map reduce functions:</p>
  
  <pre><code>var m = function(){
      // creation date
      var d = new Date(parseInt(this._id.toString().slice(0,8), 16)*1000);
      // ticks
      var t = d.getTime();
      emit(d2,d3);
  };
  
  var r = function(k,v){
      return v[0];    // just go next with ticks
  };
  
  var opts = { out :  { merge : "UserAccum", db : "Metric"},
      finalize: function(k,v){
      var str = "parseInt(this._id.toString().slice(0,8), 16)*1000 &lt;= "+v;
      return db.User.count({$where:str});         
  } 
  };
  var res = db.Provider.mapReduce(m, r, opts);
  </code></pre>
  
  <p>When run, I get error:</p>
  
  <pre><code>Sat May 12 17:47:23 uncaught exception: map reduce failed:{
      "assertion" : "invoke failed: JS Error: TypeError: db has no properties
  nofile_b:2",
      "assertionCode" : 9004,
      "errmsg" : "db assertion failure",
      "ok" : 0
  }
  </code></pre>
  
  <p>Looks like it's not possible to call db. methods inside finalize. 
  Why?</p>
  
  <p>I knoq that I can call from map() and from reduce()</p>