插入Meteor.method调用后检索_id [英] Retrieve _id after insert in a Meteor.method call
问题描述
插入文档后,我需要检索_id.
I need to retrieve the _id after insert a document.
在客户端中:
Meteor.call('saveDocument', value1, value2);
在服务器中
saveDocument: function (value1, value2) {
MyCollection.insert({ 'value1': value1, 'value2': value2});
}
我尝试在服务器端使用插入的回调函数.这样我就可以获取文档的_id,但是在回调函数中却无法返回到客户端调用:
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.
}
推荐答案
您的客户端调用应使用异步样式-来自文档
your client call should use the async style - from the docs
在客户端上,如果不传递回调并且不在存根内部,则调用将返回undefined,并且您将无法获取该方法的返回值.
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;
});
然后您只需从方法中返回ID
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
这篇关于插入Meteor.method调用后检索_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!