Reputation: 1191
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.
}
Upvotes: 26
Views: 12435
Reputation: 11
found this question when I had the same issue, got this solution use .insert() on the client side and it works fine with the callback. Something like this:
Collection.insert({
something: something //insert to Mongo
}, (error, response) => {
console.log(error, result //get the response
)});
Upvotes: 0
Reputation: 2803
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
Upvotes: 40