2014-02-17 85 views
0

我正在從mongodb中檢索Template collection的數據。所以我的問題是,當我給錯了templateName程序應該會發生錯誤。但它並沒有這樣做。程序進一步&我得到錯誤TypeError: Cannot read property 'subject' of nullTypeError:無法讀取屬性'subject'null

如何處理這件事?

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(您正在使用的客戶端庫)不會引發錯誤。 錯誤保留用於連接或語法問題。

因此必須使用它,像之前測試變量是否存在:

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。 As subject顯示爲空。

if(template.subject && template.dataMsg){ 
    // ok 
} else { 
    // wrong templateName 
} 
相關問題