diff --git a/index.js b/index.js index 62bd4ed..3750bf4 100644 --- a/index.js +++ b/index.js @@ -10,3 +10,14 @@ Mongo.Collection.prototype.aggregate = function(pipelines, options) { } return wrapAsync(coll.aggregate.bind(coll))(pipelines, options); } +Mongo.Collection.prototype.mapReduce = function(mapFunction, reduceFunction, options) { + var coll; + if (this.rawCollection) { + // >= Meteor 1.0.4 + coll = this.rawCollection(); + } else { + // < Meteor 1.0.4 + coll = this._getCollection(); + } + return wrapAsync(coll.mapReduce.bind(coll))(mapFunction, reduceFunction, options); +} diff --git a/test.js b/test.js index 960122a..72febf5 100644 --- a/test.js +++ b/test.js @@ -39,4 +39,27 @@ Tinytest.add("using some options", function(test) { ], options); test.equal(typeof result[0]['$cursor'], 'object'); -}); \ No newline at end of file +}); + +Tinytest.add("method mapReduce signature", function(test) { + var coll = new Mongo.Collection(Random.id()); + test.equal(typeof coll.mapReduce, 'function'); +}); + +Tinytest.add("let's mapReduce", function(test) { + var coll = new Mongo.Collection(Random.id()); + coll.insert({group: 1, value: 10}); + coll.insert({group: 1, value: 100}); + coll.insert({group: 2, value: 1000}); + + var mapFunction1 = function() { + emit(this.group, this.value); + }; + var reduceFunction1 = function(keyGroupId, values) { + return Array.sum(values); + }; + + var result = coll.mapReduce(mapFunction1, reduceFunction1, { out: { inline: 1 } }) + + test.equal(result, [{"_id":1,"value":110},{"_id":2,"value":1000}]); +});