我在客户端上有以下代码:
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
。
您不会在服务器方法中返回结果。不能从回调返回值。只返回清单的结果:
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 文档,插入方法返回插入文档的 ID。
在服务器上,如果您不提供回调,则插入块,直到数据库确认写入,或者在出现问题时引发异常。
你不需要返回任何东西,将流星方法改为这个。
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
的原因,如果方法出现问题,服务器将抛出错误并且流星调用将失败。
简化到最低限度:
create_checklist: function(Checklist) {
return Checklists.insert(Checklist);
}
客户端代码应看到插入文档的_id
result
不过,我不得不问,为什么?如果集合已发布,您应该能够在客户端上执行var id = Checklists.insert(Checklist)
,并让 Meteor 处理与服务器的同步。Checklists
没有发布给客户端吗?