Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve _id after insert in a Meteor.method call

Tags:

meteor

I need to retrieve the _id after insert a document.

In client:

Meteor.call('saveDocument', value1, value2);

In server

saveDocument: function (value1, value2) {
    MyCollection.insert({ 'value1': value1, 'value2': value2});
}

I have tried with the callback function of the insert in the server side. This way I can get the document's _id, but inside the callback function and this can't return to the client call:

saveDocument: function (value1, value2) {
    MyCollection.insert({ 'value1': value1, 'valu2': value2}, 
        function(err, docsInserted){ console.log(docsInserted) }); 
        //Works, but docsInserted can't return to the client.
}
like image 405
Oscar Saraza Avatar asked May 08 '13 11:05

Oscar Saraza


1 Answers

your client call should use the async style - from the docs

On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method.

Meteor.call('saveDocument', value1, value2, function(error, result){
  var theIdYouWant = result;
});

then you just return the id from the method

saveDocument: function (value1, value2) {
  return MyCollection.insert({ 'value1': value1, 'valu2': value2}); 
}

for good measure give a once over to these 2 sections of the docs

http://docs.meteor.com/#meteor_call

http://docs.meteor.com/#insert

like image 103
nate-strauser Avatar answered Nov 11 '22 10:11

nate-strauser