koolaang
koolaang

Reputation: 417

Meteor, how to pass callback and error to caller method

In my Meteor.methods I have

var post= Posts.insert({...},  function(err,docsInserted){
  Posts.update({...} , {...});
});

I want to create an insert model as suggested by David Weldon here. My model looks like this:

_.extend(Posts, {
    ins:function (docID){
      return  Posts.insert({...});
    }
});

In my methods I have this:

var post= Posts.ins(docID,  function(err,docsInserted){
  Posts.update({...} , {...});
});

How can I use a callback and error handling in the method? I'd like to be able to execute code when the Post is inserted successfully.

Upvotes: 2

Views: 426

Answers (1)

Stephen Woods
Stephen Woods

Reputation: 4049

Looking at the documentation for collection.insert:

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

Arguments

doc Object

The document to insert. May not yet have an _id attribute, in which case Meteor will generate one for you.

callback Function

Optional. If present, called with an error object as the first argument and, if no error, the _id as the second.

As I understand it, you want to execute a callback function if ins executes successfully. Given that information, here's how I'd structure the code:

_.extend(Posts, {
    ins:function (docID, callback){
      Posts.insert({...}, function( error, id ) {
          if( error ) {
            callback( error, null );
          } else {
            callback( null, id );
          }
      });
    }
});

You don't actually need to return anything. You can just execute the callback function and pass parameters along appropriately. Then you can call the function with the following code:

Posts.ins(docID,  function(err,docsInserted){
  if( error ) {
    // Handle error.
  } else {
    Posts.update({...} , {...});
  }
});

Upvotes: 2

Related Questions