我正在计算每个地区的学生人数。我有一个型号,看起来像
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_modulesmongodblibcollection.js:2961:21)
at NativeCollection.(anonymous function) [as mapReduce] (C:***node_modulesmongooselibdriversnode-mongodb-nativecollection.js:136:28)
尝试直接在模型上调用mapReduce()
方法,而不是在模型的collection属性上调用,因为该属性需要一个额外的对象作为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
管道来获得相同的结果:
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)
});
};