mongodb mapreduce作用域-ReferenceError [英] mongodb mapreduce scope - ReferenceError
问题描述
我正在尝试在mongodb map/reduce函数中使用外部对象.如果对象具有应访问的变量,则会发生错误.
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.
例如:
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
}
});
mongodb的输出:
The output from mongodb:
map reduce失败:{"errmsg":例外:ReferenceError:v不是 已定义,"代码:16722,"确定:0}在 src/mongo/shell/collection.js:970
map reduce failed:{ "errmsg" : "exception: ReferenceError: v is not defined", "code" : 16722, "ok" : 0 } at src/mongo/shell/collection.js:970
这是预期的行为吗?还有其他方法可以在mapReduce中使用外部对象吗?
Is it an expected behavior? Is there any other way to use external objects in mapReduce?
推荐答案
造成此问题的原因是此函数:
What's casuing the problem is this function:
var HelperClass = function() {
var v = [1, 2, 3];
this.data = function() {
return v.data;
};
};
因为:
return v.data;
与实际变量this.v.data
的作用域不同.
Is in a different scope to the real variable which is actually this.v.data
.
这篇关于mongodb mapreduce作用域-ReferenceError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!