【问题标题】:TypeError: Cannot read property 'subject' of nullTypeError:无法读取 null 的属性“主题”
【发布时间】:2014-02-17 09:22:53
【问题描述】:

我正在从 mongodb 检索模板集合的数据。所以我的问题是当我给出错误的templateName 时,程序应该会捕获错误。但事实并非如此。程序更进一步&我得到错误TypeError: Cannot read property 'subject' of 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;
        });

如果给出了错误的模板名称,我想将错误返回给回调函数。

【问题讨论】:

  • 你可以在第8行之前查看

标签: javascript node.js mongodb angularjs


【解决方案1】:

如果您的 find 没有返回任何文档,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;

【讨论】:

    【解决方案2】:

    您可以在第 8 行之前检查。 由于 subject 显示为空。

    if(template.subject && template.dataMsg){
        // ok
    } else {
        // wrong templateName
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 2018-09-12
      • 2021-02-27
      • 1970-01-01
      • 2022-06-19
      • 2022-01-12
      • 2021-12-04
      • 2021-12-17
      • 2022-01-09
      相关资源
      最近更新 更多