2015-12-31 116 views
1

我想獲得每個地區的學生數量。 我有一個模式,看起來像mapReduce使用node.js和貓鼬

var mongoose = require('mongoose'); 
var schema = mongoose.Schema; 
var studentSchema = new mongoose.Schema(
{ 
"name":String, 
"address" :{ 
    "locality":String 
    } 
}); 
module.exports = mongoose.model('Student', studentSchema); 

我那麼有一些Node.js的代碼

var Student = require('../../../models/Student'); 
module.exports.getStudentsBasedOnLocality = function(){ 
var o = {}; 
o.map = function() { 
    emit(Student.address.locality, 1) 
} 
o.reduce = function (k, vals) { 
    return vals.length 
} 

Student.collection.mapReduce(o, function (err, results) { 
    if(err) throw err; 
    console.log(results) 
}) 
}; 

錯誤我得到的是。有關我可能做錯什麼的提示?

類型錯誤

Cannot read property 'out' of undefined 
at Collection.mapReduce (C:\***\node_modules\mongodb\lib\collection.js:2961:21) 
at NativeCollection.(anonymous function) [as mapReduce] (C:\***\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:136:28) 

回答

1

嘗試直接調用模型上的mapReduce()方法,而不是需要一個額外的對象作爲與出屬性參數模型的集合屬性:

var Student = require('../../../models/Student'); 
module.exports.getStudentsBasedOnLocality = function(){ 
    var o = {}, 
     self = this; 
    o.map = function() { 
     emit(this.address.locality, 1) 
    }; 
    o.reduce = function (k, vals) { 
     return vals.length 
    }; 

    Student.mapReduce(o, function (err, results) { 
     if(err) throw err; 
     console.log(results) 
    }); 
}; 

另一種替代方案是使用aggregation framework,其具有bett因爲聚合在服務器本地運行(C++),而mapReduce衍生出單獨的JavaScript線程來運行JavaScript代碼。你可以這樣運行以下程序aggregation pipeline來達到同樣的效果:

var Student = require('../../../models/Student'); 
module.exports.getStudentsBasedOnLocality = function(){ 
    var pipeline = [ 
     { 
      "$group": { 
       "_id": "$address.locality", 
       "count": { "$sum": 1 } 
      } 
     } 
    ]; 

    Student.aggregate(pipeline, function (err, results) { 
     if(err) throw err; 
     console.log(results) 
    }); 
};