[SOLVED] Error: TypeError: Cannot read Property X of undefined


#1

Ok, I’m stuck. I feel like I’ve checked everything three times over here, and I just can’t see what I’m doing wrong.

I have the following code in helpers:

Template.hostList.helpers({
    hostURL: function() {
        return URLToCheck.find({});
    },
    getStatus: function() {
        try {
            let url = this.url;

            let myHostStatus = HostStatus.findOne({ "url": url }, { sort: { "runOn": -1 }});
            let runOnDate = myHostStatus.runOn;
            if (runOnDate != "") {
                let momentOnDate = moment(runOnDate).format("MM/DD/YYYY hh:mm:ss");
                Session.set("lastRunOn", momentOnDate);
            } else {
                return "Not Run Yet.";
            }

            return myHostStatus;
        } catch (error) {
            console.log("Error in getStatus call: " + error);
        }
    },
    runOnDate: function() {
        return Session.get("lastRunOn");
    }
});

I have the following information in my two collections:

Collection URLToCheck

{
        "_id" : "aqdjNRTQHHhuouZiL",
        "url" : "https://trivia-challenge.org",
        "freqCheck" : 5,
        "emailIfDown" : false,
        "emailAddress" : ""
}

and Collection HostStatus

{
        "_id" : "QGaqW3iPf8wrGsxFJ",
        "url" : "https://trivia-challenge.org",
        "status" : "Up",
        "statusColor" : "#32CD32",
        "runOn" : ISODate("2018-05-14T00:29:47.610Z")
}

I keep getting (on the client side in the console) the error:

TypeError: Cannot read property "runOn" of undefined.

and it’s at the line above
let runOnDate = myHostStatus.runOn;

I’m getting back the collection info in my query because the other values are showing up in the UI. There’s obviously a runOn value in the collection, but I can’t figure out why I keep getting this error in the console.

Any help is greatly appreciated on this.


#2

You need to make sure that your subscription to the collection HostStatus is ready, because when you call HostStatus.findOne it might return undefined if it isn’t, which would explain why you get the error you are seeing.


#3

Yeah, after doing a find() or findOne() you usually need to use a pattern like this:

let bar = baz.findOne();
let foo = bar && bar.runOn;

to make sure that you don’t try access the property of an object that’s not defined yet.