Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor collection.insert callback issues

Tags:

meteor

According to the Meteor documentation....

collection.insert(doc, [callback])

callback Function

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

...then later down...

On the server, if you don't provide a callback, then insert blocks until the database acknowledges the write, or throws an exception if something went wrong. If you do provide a callback, insert returns immediately. Once the insert completes (or fails), the callback is called with error and result arguments, same as for methods.

Which is it, error and _id or error and result? I do have Meteor.methods that are firing their callbacks correctly with error, result available to the scope.

I just can't get the callback to work correctly on a collection.insert(doc, [callback])

Either way I can't get my callback to register anything?

function insertPost(args) {
  this.unblock;
  if(args) { 
    post_text = args.text.slice(0,140);
    var ts = Date.now();  
    Posts.insert({
      post: post_text,
      created: ts
    }, function(error, _id){
      // or try function(error, result) and still get nothing 
      // console.log('result: ' + result);
      console.log('error: ' + error);
      console.log('_id: ' + _id); //this._id doesn't work either
    });

  }
  return;
}

What am I doing wrong? I have been up since 2 am coding...6 pm my time zone...I am blurry, so I might (probably) be missing something quite obvious.

Cheers Steeve

like image 243
Steeve Cannon Avatar asked May 08 '12 22:05

Steeve Cannon


2 Answers

This was a bug, fixed in the next release. Now, if you provide a callback to insert, it will be called with error and result arguments, where result is the ID of the new document, or null if there's an error.

like image 200
debergalis Avatar answered Nov 05 '22 07:11

debergalis


Since this is serverside code you can just do:

var id = Posts.insert({data}); // will block until insert is complete

and the id will be available.

like image 6
zwippie Avatar answered Nov 05 '22 06:11

zwippie