2014-02-17 5 views
0

mongodb에서 템플릿 컬렉션의 데이터를 가져옵니다. 그래서 내 문제는 내가 잘못을 줄 때이다. templateName 프로그램이 오류를 잡아야한다. 그러나 그렇게하지는 않습니다. 프로그램이 더 나아갑니다 & 나는 TypeError: Cannot read property 'subject' of null 오류가 발생합니다.TypeError : Null의 'subject'속성을 읽을 수 없습니다.

어떻게 처리할까요?

Template.findOne({ name: templateName }, function (err, template) { 
     if (err) { 
      console.log('Error occured'); 
      console.log(err.message); 
      callback(err); 
     } 
     else { 
      template_subject = template.subject; 
      template_html = template.dataMsg; 
     }); 

잘못된 templateName이 지정되면 콜백 함수에 오류를 반환하고 싶습니다.

+0

이전에 행 번호 8을 확인할 수 있습니다. – Mahavir

답변

1

Mongodb-native (사용중인 클라이언트 라이브러리)는 find가 문서를 반환하지 않은 경우 오류를 발생시키지 않습니다. 오류는 연결 또는 구문 문제에 예약되어 있습니다.

따라서 당신이 좋아하는 뭔가를 사용하기 전에 변수의 존재를 테스트해야합니다

Template.findOne({ name: templateName }, function (err, template) { 
    if (err === null && template == null) { 
     // no error, but no result found 
     err = new Error(templateName + ' not found'); 
    } 

    if (err) { 
     console.log('Error occured'); 
     console.log(err.message); 
     // early return to avoid another indentation :) 
     return callback(err); 
    } 
    template_subject = template.subject; 
    template_html = template.dataMsg; 
0

당신은 라인 전에 확인 수있는 : 8.하지 마찬가지로 제목이입니다.

if(template.subject && template.dataMsg){ 
    // ok 
} else { 
    // wrong templateName 
} 
관련 문제