类型错误:无法读取空的财产“主题” [英] TypeError: Cannot read property 'subject' of null

查看:125
本文介绍了类型错误:无法读取空的财产“主题”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从MongoDB中检索模板收集数据。所以我的问题是,当我给一个错误的 TEMPLATENAME 程序应该赶上错误。但它没有这样做。计划更进一步&安培;我得到错误类型错误:无法读取空的财产主体

I am retrieving data of Template collection from mongodb. so my problem is when i give a wrong templateName the program is supposed to catch a error. But it doesn't do so. program goes further & i get error 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;
        });

如果错误TEMPLATENAME给定,我要回错误回调函数。

If wrong templateName is given, i want to return error to callback function.

推荐答案

MongoDB的外来如果您发现没有返回任何文档将不会引发错误(您使用的客户端库)。
错误被保留用于连接或语法问题。

Mongodb-native (the client library you're using) won't raise an error if your find did not return any document. Errors are reserved for connectivity or syntax problems.

因此​​,您必须在使用它之前测试变量的存在,是这样的:

Therefore you must test the variable existence before using it, something like:

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;

这篇关于类型错误:无法读取空的财产“主题”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆