0

I have been following the example from the documentation and indeed it is easy to perform a map/reduce operation on a simple example. However, what I want to do is to create a map/reduce operation as a stored procedure and then call this on demand using mongoose. For this reason I wrote a function that looks like this and I am testing it on a small db:

function myCustomMapReduce (myCallback) {
    var o = {};
    o.map = function () { emit(this.aProperty, this.id); };
    o.reduce = function (key, values) { return values.length; };
    o.finalize = function (key, reducedValues) { return reducedValues; };
    o.out = {inline: 1};
    o.verbose = true;
    MyCollection.mapReduce(o, function (mrError, mrResults, stats) {
        console.log (' **** Finished map reduce with error ' + mrError + ' in ' + stats.processtime + ' msecs');
        console.log (JSON.stringify(mrResults, null, 3));
        return myCallback(mrError, mrResults);
    });
}

Calling the above function on runtime, indeed allows me to see a message indicating successful completion; that is, the print statement:

 **** Finished map reduce with error null in 8 msecs

and then the other console.log statement also prints an array with the results that I expect from the whole map/reduce operation. (Basically, every object in my db has a label, and I am counting the occurrences of the labels.)

Quite surprisingly, the last statement

return myCallback(mrError, mrResults);

fails! In particular I get the weird error:

TypeError: myCallback is not a function

Can you help me understand why this is happening? Should I pass an additional parameter to the object o that has the specifications of the map/reduce operation that I want to perform? This error is very strange, because myCallback is a parameter to the function myCustomMapReduce and immediately before the return command, both mrError and mrResults contain valid information that has been computed by the map/reduce operation.

Honestly, I do not get it. At the point where the error is thrown, the whole map/reduce operation has finished and I am attempting to perform a standard use of a callback function in order to return the results to the caller. How can I return the results mrResults to the function that made the call to the above procedure?

MightyMouse
  • 13,208
  • 8
  • 33
  • 43
  • 1
    How are you actually calling the `myCustomMapReduce()` function? You should be doing something like `myCustomMapReduce(function(err,result) { // do something with reponse })`. Your usage of `return` leads me to suspect you are not. – Blakes Seven Apr 07 '16 at 23:50
  • You are right, I had forgotten an additional argument that I was passing the first time that I wrote the function. Please post below and I will accept. – MightyMouse Apr 07 '16 at 23:52

0 Answers0