title: MongoDB dynamic variables in MapReduce
body: <p>I have node.js router for mongodb mapreduce:</p>
  
  <pre><code>app.get('/api/facets/:collection/:groupby', function(req, res) {
      var collection = db.collection(req.params.collection);
      var groupby = req.params.groupby;
      var map = function() {
        if (!this.region) {
          return;
        }
        for (index in this.region) {
          emit(this.region[index], 1);
        }
      }
      var reduce = function(previous, current) {
        var count = 0;
  
        for (index in current) {
          count += current[index];
        }
        return count;
      }
      var options = {out: groupby + '_facets'};
      collection.mapReduce(map, reduce, options, function (err, collection) {
      collection.find(function (err, cursor) {
          cursor.toArray(function (err, results) {
                  res.send(results);
              });            
      })
      })
  });
  </code></pre>
  
  <p>This works good. But I want to use my <code>groupby</code> param. When I try to do something like this:</p>
  
  <pre><code>  var map = function() {
      if (!this[groupby]) {
              return;
          }
      for (index in this[groupby]) {
              emit(this[groupby][index], 1);
          }
    }
  </code></pre>
  
  <p>I receive <code>TypeError: Cannot call method 'find' of undefined</code>. Is there any way to create such dynamic mapreduce function?</p>
  
  <p>Thanks.</p>
  
  <p><strong>Edited:</strong></p>
  
  <p>Wow! I do it myself. Just pass <code>scope</code> param to mapreduce argument like so <code>scope:{keys: groupby}</code> and then I was able to do <code>var key = this[keys]</code> inside map function and use <code>key</code> variable instead <code>this.region</code>. Great!</p>