2013-03-18 31 views
4

MongoDB的动态变量,我对MongoDB的MapReduce的node.js的路由器:中的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); 
      });    
    }) 
    }) 
}); 

这工作不错。但我想用我的groupby参数。当我尝试做这样的事情:

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

我收到TypeError: Cannot call method 'find' of undefined。有什么办法可以创建这样的动态mapreduce函数吗?

谢谢。

编辑:

哇!我自己做。只需将scope param传递给mapreduce参数,如scope:{keys: groupby},然后我就可以做var key = this[keys]里面的map函数,并用key变量代替this.region。大!

+1

你应该发布并接受你的答案。 – generalhenry 2013-03-18 22:42:15

+1

@generalhenry同意它将在未来帮助他人,请张贴答案并接受OP :) – Sammaye 2013-03-18 22:57:28

回答

3

哇!我自己解决了它。我只是将范围参数传递给mapreduce参数。

scope:{keys: groupby} 

然后,我能够做

var key = this[keys] 

地图功能里面和使用关键变量,而不是this.region。大!