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!
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!