mapReduce using node.js and mongoose
Try calling the mapReduce()
method directly on the model, not on the collection property of the model which requires an extra object as parameter with the out property:
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) });};
Another alternative is to use the aggregation framework, which has better performance since aggregation runs natively in the server (C++), whereas mapReduce spawns separate javascript thread(s) to run JavaScript code. You can thus run the following aggregation
pipeline to achieve the same result:
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) });};