简体   繁体   English

mongodb mapreduce作用域-ReferenceError

[英]mongodb mapreduce scope - ReferenceError

I'm trying to use an external object inside mongodb map/reduce functions. 我试图在mongodb map / reduce函数中使用外部对象。 If the object has a variable which it should access, an error occurs. 如果对象具有应访问的变量,则会发生错误。

For example: 例如:

var conn = new Mongo();
var db = conn.getDB("test");

var HelperClass = function() {
  var v = [1, 2, 3];

  this.data = function() {
    return v;
  };
};

var helper = new HelperClass();

var map = function() {
  helper.data().forEach(function(value) {
    emit(value, 1);
  });
};

var reduce = function(key, values) {
  var count = 0;
  values.forEach(function(entry) {
    count += entry;
  });
  return count;
};

db.test.mapReduce(map, reduce, {
  out: "temp",
  scope: {
    helper: helper
  }
});

The output from mongodb: mongodb的输出:

map reduce failed:{ "errmsg" : "exception: ReferenceError: v is not defined", "code" : 16722, "ok" : 0 } at src/mongo/shell/collection.js:970 映射减少失败:{“ errmsg”:“例外:ReferenceError:未定义v”,“代码”:16722,“确定”:0},位于src / mongo / shell / collection.js:970

Is it an expected behavior? 这是预期的行为吗? Is there any other way to use external objects in mapReduce? 在mapReduce中还有其他使用外部对象的方法吗?

What's casuing the problem is this function: 造成此问题的原因是此功能:

var HelperClass = function() {
  var v = [1, 2, 3];

  this.data = function() {
    return v.data;
  };
};

Since: 以来:

return v.data;

Is in a different scope to the real variable which is actually this.v.data . 与实际变量this.v.data范围不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM