【问题标题】:Map Reduce not giving results for NodeJS MongoDB native driverMap Reduce 没有给出 NodeJS MongoDB 本机驱动程序的结果
【发布时间】:2016-07-06 06:48:46
【问题描述】:

我在 NodeJS 中的 map-reduce 函数是这样的:

 exports.getDistinctURLCount = function(params, callback){
    var mapFunction = function(){
        var bucket = 10;
        emit(Math.floor(parseInt(this.xyz)/bucket), {count: 1});
    };

    var reduceFunction = function(key, values){
     var urlCount = 0;
     if(values != undefined){
       values.forEach( function(value) {
         urlCount += value.count ;
       });
     }
     return urlCount;
    };

    var finalizeFunction = function (key, reducedVal) {
       if(isNaN(reducedVal)){
        return reducedVal.count
       }else{
        return reducedVal
       }
      };

    var output = {
       out: {"inline":1},
       finalize: finalizeFunction
      };

      return mongoMan.mapReduceFunction("clients", mapFunction, reduceFunction, output, function(err, result){
        if(err){
          callback(err, null);
        }else{
          console.log(result);
          callback(null, result);
        }
 }

MongoMan 是一个不同的文件,它接受 map-reduce 函数:

exports.mapReduceFunction = function(collection, map, reduce, options, callback){
  _getModel(collection).mapReduce(map, reduce, options, function(err, docs){
    _prepResponse(err, docs, callback);
  });
}

map reduce 查询在 Mongo Shell 中成功运行,但是当通过 NodeJS 调用时,它不会产生任何结果。甚至没有空白。

我在传递 map、reduce 函数时做错了吗?

【问题讨论】:

    标签: node.js mongodb mapreduce


    【解决方案1】:

    有两个问题:

    将函数作为参数传递给另一个函数 -

    return mongoMan.mapReduceFunction("clients", mapFunction.toString(), reduceFunction.toString(), output, function(err, result){
        if(err){
          callback(err, null);
        }else{
          console.log(result);
          callback(null, result);
        }
    

    另一个问题是变量的范围 - 参考这里How to use variables in MongoDB Map-reduce map function

    另外,我正在使用 Mongoose。所以,这里是 mapReduce 在 Mongoose 中的处理方式 - Mongoose API

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2014-06-29
      相关资源
      最近更新 更多