Mongoose mapreduce:使用array.some映射函数



这个Javascript在我的映射函数之外运行良好

var cribs = ["list","tree"];
if ( cribs.some(function(i){return (new RegExp(i,'gi')).test("a long list of words");}) ) {
 console.log('match');
}

(它只是用数组中的值搜索一个字符串)。

尽管在我的地图功能中使用它不起作用:

var o = {};
o.map = function () { 
    if ( cribs.some(function(i){return (new RegExp(i,'gi')).test(this.name);}) ) {
        emit(this, 1) ;
    }
}
o.out = { replace: 'results' }
o.verbose = true;
textEntriesModel.mapReduce(o, function (err, model, stats) {
    model.find(function(err, data){
        console.log(data);
    });
})

它不发出任何东西,所以我有一个空的结果集。没有错误。

如果我不使用array.some,而只是使用一个普通的正则表达式,那么它工作得很好:

o.map = function () { 
    if(this.name.match(new RegExp(/list/gi))) {
        emit(this, 1) ;
    }
}

所以我的问题是,为什么上面的array.some函数不能在我的map函数中工作?

我有一长串需要匹配的单词,所以我真的不想单独为它们编写正则表达式,上面的应该起作用。

以下是我试图在map函数中使用的函数的jsfiddle:http://jsfiddle.net/tnq7b/

您需要将cribs添加到scope选项中,使其可用于map函数:

var cribs = ["list","tree"];
var o = {};
o.map = function () { 
    if (cribs.some(function(i){return (new RegExp(i,'gi')).test(this.name);})) {
        emit(this, 1);
    }
}
o.out = { replace: 'results' };
o.scope = { cribs: cribs };
o.verbose = true;
textEntriesModel.mapReduce(o, function (err, model, stats) {
    model.find(function(err, data){
        console.log(data);
    });
});

最新更新