Trying to use the monbro:mongodb-mapreduce-aggregation
to run a super simple mapReduce function. While it works great the first time around, subsequent calls I get the following error:
I20150608-11:11:05.294(-4)? Exception while invoking method 'exportDonations' Error: A method named '/donation_totals_by_donor/insert' is already defined
I20150608-11:11:05.294(-4)? at packages/ddp/livedata_server.js:1461:1
I20150608-11:11:05.294(-4)? at Function._.each._.forEach (packages/underscore/underscore.js:113:1)
I20150608-11:11:05.294(-4)? at [object Object]._.extend.methods (packages/ddp/livedata_server.js:1459:1)
I20150608-11:11:05.294(-4)? at [object Object].Mongo.Collection._defineMutationMethods (packages/mongo/collection.js:904:1)
I20150608-11:11:05.294(-4)? at new Mongo.Collection (packages/mongo/collection.js:209:1)
I20150608-11:11:05.295(-4)? at [object Object].ns.Collection (packages/matb33:collection-hooks/collection-hooks.js:190:1)
I20150608-11:11:05.295(-4)? at [object Object].Meteor.methods.exportDonations (app/server/index.js:44:19)
I20150608-11:11:05.295(-4)? at [object Object].methodMap.(anonymous function) (packages/meteorhacks:kadira/lib/hijack/wrap_session.js:160:1)
I20150608-11:11:05.295(-4)? at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1617:1)
I20150608-11:11:05.295(-4)? at packages/ddp/livedata_server.js:648:1
Here's my Meteor method:
var Reduced = new Mongo.Collection("donation_totals_by_donor");
var map = function() {
if(!this.donor) {
return;
}
emit(this.donor, this.amount);
}
var reduce = function(donorId, totalAmount) {
return Array.sum(totalAmount);
}
var result = Donations.mapReduce(
map,
reduce,
{
query: { createdAt: { $gte: new Date('Jan 1, ' + year), $lt: new Date('Jan 1, ' + (year + 1)) } },
out: "donation_totals_by_donor",
verbose: true
}
);
return Reduced.find({}).fetch();
This error is the result of defining your collection multiple times. You need to move the
new Mongo.Collection
code outside of the method.Typically you'd define your collections in a central location, e.g.
lib/collections/mycollection.js
. However, because this code is only running on the server you could just keep it at the top of this file or put it somewhere likeserver/collections/reduced.js
.