mapReduce使用node.js和mongoose
我正在设法计算每个地区的学生人数。 我有一个模型 ,看起来像
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) }) };
我得到的错误是。 任何提示,我可能做错了什么?
TypeError :
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)
尝试直接在模型上调用mapReduce()
方法,而不是模型的集合属性,而需要使用out属性的额外对象作为参数:
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) }); };
另一种方法是使用聚合框架 ,由于聚合在服务器(C ++)中本地运行,所以聚合框架具有更好的性能,而mapReduce衍生单独的JavaScript线程来运行JavaScript代码。 您可以运行以下aggregation
pipe道来获得相同的结果:
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) }); };