Thank you! Your feedback has been delivered
Thank you! Your feedback has been sent

Performing aggregation using meteor-mongo-extensions

I've installed the meteor-mongo-extensions package and was able to perform an aggregation in the meteor mongo shell and get the result that I expected.

db.ratings.aggregate([ {$match: {postId:"D7f3WoDEGW3SqGKW9"} }, {$group: { _id: null, "avgRating":{$avg: "$rateVal"} } } ]);

{ "result" : [ { "_id" : null, "avgRating" : 4 } ], "ok" : 1 }

However I get "undefined" when I perform the same within a meteor method...

rate: function(ratingProp){
    var user = Meteor.user();
    var postId = ratingProp.postId;
    var post = Posts.findOne({_id: postId});
    var rateVal = ratingProp.rateVal;

// ensure the user is logged in
if (!user) {
    throw new Meteor.Error(401, "You need to signin to rate.");

// ensure rating has rateVal
if (!rateVal){
    throw new Meteor.Error(422, "No rating provided.");

// ensure rating has a post
if (!post){
    throw new Meteor.Error(422, "Rating not associated with a post.");

Ratings.upsert({userId: user._id, postId: postId}, 
                {$set: { rateVal: rateVal }}

// perform aggregation
var avgRate = Ratings.aggregate([
        // hard coded for testing
        {postId: "D7f3WoDEGW3SqGKW9"}
            _id: null,
            "avgRating":{$avg: "$rateVal"}

 // additional code...

I assume that I'm missing something fundamental. How should the aggregation be performed? Any advice or suggestions would be great.

Note: This question is sponsored by CodersClan and has been originally posted on Stack Overflow by hippomoe

User Gravatar


Posted Oct 14 2013 19:24 UTC


  • Assigned To Conner
  • Solved
  • meteor

1 Replies

Most importantly, note that db.ratings.aggregate has not a thing to do with meteor or meteor-mongo-extensions . Mongo itself has a native db.<collection>.aggregate() function. So thats why it works in the shell.

Now for Meteor. Meteor uses a custom mongo driver so it can set up all the nice reactive aspects in Meteor.Collection(), among other things. As such, some of the mongo functions have not yet been implemented.

And finally meteor-mongo-extensions, that is effectively a hack of a hack. I have yet to confirm it I believe the issue can be found in this Github issue. Try to run this on the server outside the meteor method, just to be sure.

If your issue is that the package is broken you can try one of the many packages on Atmosphere that manage aggregation. mongodb-server-aggregation looks promising.

User Gravatar


Posted Oct 15 2013 20:29 UTC


This didn't solve your task? Get your own custom solution.

Add a reply

By posting a reply on CodersClan you agree to our Terms & Conditions