0

So I've just started with Meteor and really JavaScript so forgive the messy coding as I am new to all of this please. I'm using a Mongo Aggregation to do some server side math and the method is returning undefined on the client but the server-side console log is returning the correct information. Here is the server method...

Meteor.methods({
'schoolHealth': function() {
var pipeline = [
  {
    "$group": {
      "_id": null,
      "total": { "$avg": "$roomHealth"}
    }
  }
];
Equipment.aggregate(pipeline, function(err, result) {
  if (err) {
    throw err;
    console.log("Error in finding school health average:" + result);
  } else {
    console.log(result[0].total)
    return result[0].total;
  }
});
}
});

And on the client...

Meteor.call('schoolHealth', function(error, result) {
if (error) {
  console.log(error);
} else {
  console.log(result);
  Session.set('health', result);
}
});

I'm calling the Session on a blaze template but the method is failing before that happens. Also, I have tried not using a Session and the result is the same. I have read into Sync vs. Async but I don't know enough about it to know if I am doing something wrong there. Thanks ahead of time for the help.

  • This question gets asked all the time. The problem is with your `return` statement. The method doesn't stop until return gets called; when it reaches its end it return undefined. The return statement nested in your aggregate is meaningless. – Christian Fritz Sep 10 '16 at 17:26
  • 1
    Also see: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call; http://stackoverflow.com/questions/36393229/why-does-my-meteor-method-return-undefined; http://stackoverflow.com/questions/31664423/why-is-undefined-being-returned-for-meteor-call-in-client – Christian Fritz Sep 10 '16 at 17:30
  • Why would it return on the server then? – Joshua Burkhalter Sep 10 '16 at 17:31
  • no idea, but your code is wrong ;-) – Christian Fritz Sep 10 '16 at 19:05

0 Answers0