mongodb mapreduce scope - ReferenceError

空扰寡人 提交于 2019-12-13 00:12:41

问题


I'm trying to use an external object inside mongodb map/reduce functions. 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:

map reduce failed:{ "errmsg" : "exception: ReferenceError: v is not defined", "code" : 16722, "ok" : 0 } at src/mongo/shell/collection.js:970

Is it an expected behavior? Is there any other way to use external objects in mapReduce?


回答1:


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.



来源:https://stackoverflow.com/questions/21522927/mongodb-mapreduce-scope-referenceerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!