-1

The following error occours

Thu May 23 07:14:53.437 JavaScript execution failed: map reduce failed:{
    "errmsg" : "exception: JavaScript execution failed: TypeError: Cannot read property 'product_category' of undefined near '(values[i].product_category)'  (line 21)",
    "code" : 16722,
    "ok" : 0
 at src/mongo/shell/collection.js:L970

My map and reduce function are:

map1 = function()
{ 
   emit({Product_id:this.Product_id
}, 
{
   product_category:this.product_category
}); 
}

reduce1 = function(key, values)
{
var ref = new Array();
var count = 0;
var tmp="";
var pdt_array = new Array();
for (var i = 1; i <= values.length; i++) {                                 
if( i == 1 )
{
     pdt_array_array[i] = values[i];
} 
else
{                     
    tmp = values[i];
    while(i > 1)
    {
        if(tmp == pdt_array[i])
        {
            ref.push(values[i].product_category);
            count++;
        }
        i--;

    }
    pdt_array[i] = tmp;
    tmp = "";
}
}
   return {product_category:ref, Count:count}
}

db.DummyReverse.mapReduce(map1, reduce1, {out:{reduce:"product_count_while"}})
Emii Khaos
  • 9,983
  • 3
  • 34
  • 57

2 Answers2

2

The issue is that you are not returning the same format from reduce function as you are emitting as value. Since reduce function can be called 0, once or multiple times for each key you must use the exact same format in all of those cases and you cannot assume that your reduce function will be called only once.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
0

Javascript arrays are 0-indexed. So your last for-run want to access a array index, which doesn't exist. I hope I interpret your code right.

[...]

for (var i = 0; i < values.length; i++) {                                 
    if ( i == 0) {
         pdt_array_array[i] = values[i];
    } else {                     
        tmp = values[i];

        while(i > 0) {
            if(tmp == pdt_array[i]) {
                ref.push(values[i].product_category);
                count++;
            }

            i--;
        }

        pdt_array[i] = tmp;
        tmp = "";
    }
}

[...]

Take notice at for (var i = 0; i < values.length; i++). So the n-th element has the index n-1. The last element length-1.

Remarks: Are you sure you get no infinite loop with the for-loop increasing i and in the while decreasing it?

Emii Khaos
  • 9,983
  • 3
  • 34
  • 57