这是我从终端
获得的错误Exception while invoking method 'getCustomerNameByAppIdReactive' { stack: 'TypeError: Cannot read property \'customerId\' of undefined
at [object Object].getCustomerNameByAppIdReactive (server/Functions/searchFunctions.js:167:20)
at [object Object].methodMap.(anonymous function) (packages/meteorhacks_kadira/lib/hijack/wrap_session.js:164:1)
at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1711:12)
at packages/ddp-server/livedata_server.js:711:19
at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
at packages/ddp-server/livedata_server.js:709:40
at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
at packages/ddp-server/livedata_server.js:707:46
at tryCallTwo (/home/saran/.meteor/packages/promise/.0.7.3.3xbt0b++os+web.browser+web.cordova/npm/node_modules/promise/lib/core.js:45:5)
at doResolve (/home/saran/.meteor/packages/promise/.0.7.3.3xbt0b++os+web.browser+web.cordova/npm/node_modules/promise/lib/core.js:200:13)', I20170824-11:47:30.445(5.5)? source: 'method' }
这是我在服务器上写的meteor方法
getCustomerNameByAppIdReactive: function(appointmentId){
let customerId = Appointments.findOne({
_id: appointmentId}).customerId;
if (customerId == “1”){
return “Walk-In Customer”;
} else {
return Customers.findOne({_id:customerId}).name;
}
},
这是来自客户的反应方法调用
getCustomerName: (appointmentId)=>{
return ReactiveMethod.call(“getCustomerNameByAppIdReactive”,appointmentId);
},
此方法工作正常,但在终端中将错误视为
"Exception while invoking method ‘getCustomerNameByAppIdReactive’ { stack: 'TypeError: Cannot read property ‘customerId’ of undefined\n at [object Object].getCustomerNameByAppIdReactive (server/Functions/searchFunctions.js:167:20)\n at [object Object].methodMap.(anonymous function) "
如果你与这个问题有关系吗?
答案 0 :(得分:1)
使用if条件检查是否有返回值。如果返回值为null或未定义,则会出现异常
let customerId = Appointments.findOne({_id: appointmentId}).customerId;
if(customerId){
}
else{
}
答案 1 :(得分:0)
您的代码假定会找到一条记录,但最好是在编码时保持防御,并假设事情可能出错,这是您的代码:
getCustomerNameByAppIdReactive: function(appointmentId){
let customerId = Appointments.findOne({
_id: appointmentId}).customerId;
if (customerId == “1”){
return “Walk-In Customer”;
} else {
return Customers.findOne({_id:customerId}).name;
}
},
对Appointments.findOne的调用将返回一条记录,但它返回null / undefined。因此错误消息:
无法读取属性\' customerId \'未定义的
如果您将代码重组为防御性代码,则会产生更好的结果,例如
getCustomerNameByAppIdReactive: function(appointmentId){
let appt = Appointments.findOne({
_id: appointmentId});
if (!appt) {
console.log("Can't find an appointment record for "+appointmentId)
return "Not found"
}
if (appt.customerId === “1”){
return “Walk-In Customer”;
} else {
return Customers.findOne({_id:customerId}).name;
}
},
您可以在Customers.findOne电话上写一些更具防御性的代码,但我会留下您的帮助。
此代码现在不会爆炸(除非找不到客户)