You Hock Tan
You Hock Tan

Reputation: 1015

Meteorjs method call return undefined even though having callback

i'm playing with meteorjs and had a hard time trying to figure out what exactly happen to the async method i written.

//in methods.js
feedbackTag = new Meteor.Collection('feedbackTag');

Meteor.methods({
  searchTag: function (tag, collections) {
    var result;
    if(collections.toLowerCase() == 'feedback')
    {
    result = feedbackTag.find({tag: tag});
    }
    return result;
  }
});

//in client.js
  Template.executefb.events({
'keyup input#searchFeedback': 
  function(e) { 
    if(e.which == '13')
    {
      var tag = $('#searchFeedback').val();
      Meteor.call('searchTag', tag, 'feedback', function(err, data){
        //err returns:Internal server error, data returns undefined
        console.log(err, data) 
      });
    }
  }
});

I seriously had no idea why does it return an internal server error:500. Any advice please.

Thanks in advance!

Update:

I realised that the results becomes 'undefined' when it was called in the client side. However, if I called directly from client i.e.

var result = feedbackTag.find({tag: tag});

it returns me the data I want.

Any ideas how to get the results from methods class instead? Thanks

Upvotes: 0

Views: 599

Answers (1)

rvr_jon
rvr_jon

Reputation: 209

Try adding .fetch() to your collection call on the server. This will return an actual array of data, otherwise you're returning a cursor, like you would in Meteor.publish().

This might be what's causing the error.

    Meteor.methods({
      searchTag: function (tag, collections) {
        if(Match.test(tag, String) && Match.test(collections, String) {
          if(collections.toLowerCase() === 'feedback') {
            return feedbackTag.find({tag: tag}).fetch();
          } else {
            console.log("Should have sent feedback, sent " + collections);
          } 
        } else {
          throw new Meteor.Error(400, "Invalid inputs!");
      }
    });

I've modified your code a bit, because it would be wise to start throwing your own errors, and it would also be wise to use Meteor's new Match package to validate your inputs.

Methods will return either an error object or a response object. Usually you'll have a condition on the receiving end, instead of trying to show both like you did with console.log.

function(err, res) { 
  if(!!err) { 
    alert(err.reason); /* or console.log(err) */
  } else {
    console.log(res);
  }
}

Upvotes: 3

Related Questions