MongoDB javascript pass argument-Collection of common programming errors

This line:

db.smsdb.mapReduce(map(2), reduce, "collection")

is calling map(2) with the result (undefined) being passed as the map function for mapReduce.

Instead do something like this:

db.smsdb.mapReduce(function(){ map.call(this, 2); }, reduce, "collection")

UPDATE

The above doesn’t work because the map function isn’t available in the scope the mapReduce map function is run. So you have to wrap it up into a single function that can generate the map function you need:

var mapper = function(n) {
    function map() {
        if(this.x == n){
            emit(this.x);
        }
    }
    return map;
};
db.smsdb.mapReduce(mapper(2), reduce, "collection");

Originally posted 2013-11-10 00:15:20.