4

I have node.js router for mongodb mapreduce:

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);
            });            
    })
    })
});

This works good. But I want to use my groupby param. When I try to do something like this:

  var map = function() {
    if (!this[groupby]) {
            return;
        }
    for (index in this[groupby]) {
            emit(this[groupby][index], 1);
        }
  }

I receive TypeError: Cannot call method 'find' of undefined. Is there any way to create such dynamic mapreduce function?

Thanks.

Edited:

Wow! I do it myself. Just pass scope param to mapreduce argument like so scope:{keys: groupby} and then I was able to do var key = this[keys] inside map function and use key variable instead this.region. Great!

2
  • 1
    You should post and accept your answer. Commented Mar 18, 2013 at 22:42
  • 1
    @generalhenry Agreed it will help others in future, please post answer and accept OP :) Commented Mar 18, 2013 at 22:57

1 Answer 1

3

Wow! I solved it myself. I just passed a scope param to the mapreduce argument.

scope:{keys: groupby} 

Then I was able to do

var key = this[keys] 

inside map function and use key variable instead of this.region. Great!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.