Meteor.call回调函数返回未定义

时间:2015-04-24 03:24:15

标签: javascript node.js mongodb meteor

我在客户端上有这个代码:

var Checklist = {
            title: this.title,
            belongs_to: this.belongs_to,
            type: this.type,
            items: this.items
        };
        Meteor.call(
            'create_checklist',
            Checklist,
            function(error,result){
                console.log('error',error,'result',result);
                // if(!error) {
                //  Router.go('/checklist/'+response);
                // }
            }
        );

这在服务器上:

create_checklist: function(Checklist) {
        Checklists.insert(
            {
                title: Checklist.title,
                belongs_to: Checklist.belongs_to,
                type: Checklist.type,
                items: Checklist.items
            }, function(error,id){
                console.log(error,id);
                if(id) {
                    return id;
                } else {
                    return error;
                }
            }
        );
    },

在创建核对表时,Meteor.call会将信息成功传递给服务器。我可以在服务器控制台中看到新核对表的ID。但是,客户端只会看到undefined错误和结果。

3 个答案:

答案 0 :(得分:5)

您不会在服务器方法中返回结果。您无法从回调中返回值。返回Checklists.insert的结果:

create_checklist: function(Checklist) {
        return Checklists.insert(
            {
                title: Checklist.title,
                belongs_to: Checklist.belongs_to,
                type: Checklist.type,
                items: Checklist.items
            }, function(error,id){
                console.log(error,id);
                if(id) {
                    return id;
                } else {
                    return error;
                }
            }
        );
    },

根据Meteor docs insert 方法返回插入文档的ID。

在服务器上,如果您不提供回调,则插入块直到数据库确认写入,或者如果出现错误则抛出异常。

答案 1 :(得分:1)

你不需要返回任何东西,将流星方法更改为此。

create_checklist: function(Checklist) {
        Checklists.insert(
            {
                title: Checklist.title,
                belongs_to: Checklist.belongs_to,
                type: Checklist.type,
                items: Checklist.items
            }
        );
    }

meteor.call callback知道如何处理服务器响应这就是你使用error result的原因,如果方法出错会导致服务器抛出错误并且流星调用将失败。

答案 2 :(得分:0)

简化到最低限度:

create_checklist: function(Checklist) {
  return Checklists.insert(Checklist); 
}

您的客户端代码应在_id

中看到插入文档的result

我不得不问,为什么?如果集合已发布,您应该能够在客户端上执行var id = Checklists.insert(Checklist),并让Meteor处理与服务器的同步。 Checklists是否未发布给客户?

相关问题