【发布时间】:2012-07-26 01:16:04
【问题描述】:
我想制作一些在 mongo 中执行参数化映射/减少作业的 javascript 函数,但我对 JavaScript 的作用域感到困惑。例如,下面的代码给了我"gender" 变量的计数;即它会告诉我有多少 "male" 和 "female" 记录:
// count categories
db.responses.mapReduce(
function(){
emit(this["gender"], {count: 1})
}, function(state, values){
var result = {count: 0};
values.forEach(function(value) {
result.count += value.count;
});
return result;
}, {out: { inline : 1}}
);
这工作得很好。在下一步中,我想创建一个对任意属性执行此操作的函数
function countCategories(item) {
function mapper(it){
fn = function(){
if(this[it]){
emit(this[it], {count: 1});
}
};
return fn;
}(item);
var reducer = function(state, values){
var result = {count: 0};
values.forEach(function(value) {
result.count += value.count;
});
return result;
};
var out = {out: { inline : 1}};
var results = db.responses.mapReduce(
mapper,
reducer,
out
);
return results;
}
countCategories("gender")
但是当我尝试时:
countCategories("gender")
{
"results" : [ ],
"timeMillis" : 48,
"counts" : {
"input" : 2462,
"emit" : 0,
"reduce" : 0,
"output" : 0
},
"ok" : 1,
}
从未调用过 emit 函数。这里出了什么问题?我的猜测是 mongo 提供的 emit 函数的作用域,但我不太确定为什么它没有被调用,也没有抛出错误。
【问题讨论】:
-
你根本不需要闭包,
item已经在countCategories的范围内定义了。为什么不直接将fn分配给mapper? -
因为没用...顺便把问题改了一下。
-
当然,这不是一个解决方案...
标签: javascript node.js mongodb closures mongoose