【问题标题】:Error while executing mapreduce in mongo-shell在 mongo-shell 中执行 mapreduce 时出错
【发布时间】:2013-05-23 15:45:55
【问题描述】:

出现以下错误

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

我的map和reduce函数是:

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"}})

【问题讨论】:

    标签: javascript mongodb mapreduce mongo-shell


    【解决方案1】:

    问题是您从reduce 函数返回的格式与您作为值发出的格式不同。由于可以为每个键调用 0、一次或多次 reduce 函数,因此在所有这些情况下,您必须使用完全相同的格式,并且您不能假设您的 reduce 函数只会被调用一次。

    【讨论】:

      【解决方案2】:

      Javascript 数组是 0 索引的。所以你最后一次运行想要访问一个不存在的数组索引。我希望我能正确解释您的代码。

      [...]
      
      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 = "";
          }
      }
      
      [...]
      

      注意for (var i = 0; i &lt; values.length; i++)。所以第 n 个元素的索引为n-1。最后一个元素length-1

      备注:你确定你没有无限循环,for-loop 增加i 并在 while 减少它?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-12
        • 2014-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-10
        相关资源
        最近更新 更多