Methods: Get param on method completion (successful or otherwise) [Solved]

Hi,

I’ve been using this pattern from the guide, and its been working really well. However, how do i get information back from making these calls?

So for example, if i make a call to a method, as:

const foo = {}; // Some complex object
<someMethod>.call(foo, (err, res) => {
  if(err) {
    // some stuff on error handling...
  } else {
    // success
  }
});
  1. What is res above?
  2. Lets day the method was an <someCollection>.insert(). How would i get back the _id of the object that just got inserted? So a new foo record got created in Mongo, now I need it’s id. How do I do this?

Thanks so much in advance.
Tat

Also, if anyone can suggest a good pattern for implementing the call back nicely (with Error handling) it would be most appreciated. I read the bit on Error Handling in the guide, and am not sure the use cases where you would use Meteor.Error over a normal JS Error (i.e. why one or the other?)

Thanks…

res is whatever you returned from the method (the result).

Meteor.methods({
  doInsert() {
    return MyCollection.insert(someObject);
  }
});

If you check [the insert docs](http://docs.meteor.com/api/collections.html#Mongo-Collection-insert) you will see that the `_id` is returned, so the above code returns that back to the client.

> Insert a document in the collection. Returns its unique _id.

[quote="tathagatbanerjee, post:2, topic:28046"]
Also, if anyone can suggest a good pattern for implementing the call back nicely (with Error handling) it would be most appreciated. I read the bit on Error Handling in the guide, and am not sure the use cases where you would use Meteor.Error over a normal JS Error (i.e. why one or the other?)
[/quote]

There's a [good article from meteoruniversity here](https://meteoruniversity.org/handling-publication-errors/) which explains that very well (covers publications and methods).

Thanks so much Rob. Simply using return before the insert solved the problem nicely. Its hard to believe I did not realise this earlier.

I tried the below earlier, but because I was not returning anything originally, well no result would come back, so I could not work out what it was doing. Once added in the return, it worked exactly as expected.

<method>.call(<object>, (err, result) => { 
  // doSomething()
}); 

Many thanks in addition to pointing out the article at Meteor University. I’ll spend some time looking at it. Thanks so much.

Tat

1 Like