在插入 Meteor.method 调用后检索 _id [英] Retrieve _id after insert in a Meteor.method call

查看:20
本文介绍了在插入 Meteor.method 调用后检索 _id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在插入文档后检索 _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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆