TypeError:无法读取属性

时间:2015-05-06 23:01:42

标签: javascript mongodb

我收到以下错误:

2015-05-06T15:51:43.332-0700 map reduce failed:{
"errmsg" : "exception: TypeError: Cannot read property 'Dockey' of undefined near 'essaged[0].Dockey) {         return;     ' ",
"code" : 16722,
"ok" : 0
} at src/mongo/shell/collection.js:1224

以下是我运行的脚本是针对mongo db运行的Map Reduce脚本。

function mapFunction() {
    if (!this.eventdata || !this.eventdata.Messaged || this.eventdata.Messaged.length === 0 || !this.eventdata.Messaged[0].Dockey) {
        return;
    }
    emit({
        entityid: this.entityid,
        eventType: this.eventType,
        profileid: (this.eventdata.Messaged[0].Dockey || this.eventdata.Messaged[0].PID)
    }, {
        datecreated: this.datecreated
    });
}

function reduceFunction(key, values) {
    var reducedValue = values[0],
        i;

    for (i = 1; i < values.length; i++) {
        if (values[i].datecreated > reducedValue.datecreated) {
            reducedValue = values[i];
        }
    }

    return reducedValue;
}



var res = db.TRACKING_DATA.mapReduce(mapFunction,
    reduceFunction, {
        out: {
            reduce: "LASTCONNECTED_ALLTYPES"
        },
        query: {
            datecreated: {
                $gt: ISODate("2015-03-11T18:00:00.000Z")
            }
        },
    }
)

以下是该系列的文档条目:

"_id": "0003e88f-37ed-493c-930e-f401821faca1",
"_class": "com.daoservice.model.TrackingData",
"modified": ISODate("2015-03-03T22:00:04.679Z"),
"eventtype": "@Connect button clicked and default email tab opened",
"eventdata": {
    "Messaged": [{
        "ViewedID": "4918faab-2eca-4b36-8ca7-342f064a4699",
        "Dockey": "ad30d3c827e2f1f44d4bae598ac14093",
        "PID": "",
        "UID": "",
        "connectDate": ISODate("2015-03-03T22:00:04.676Z"),
        "connectID": "fcd6d2cb-1f2d-43ac-b42d-deec7f5d7931",
        "urlClicked": "",
        "email": ""
    }]
},
"eventsource": "Customer App",
"sourceip": "210.7.77.202",
"entityid": "1652430",
"groupid": "15013",
"datecreated": ISODate("2015-03-03T22:00:04.674Z")

1 个答案:

答案 0 :(得分:0)

Messaged数组没有成员,但您在最后一个条件中尝试直接访问一个成员!this.eventdata.Messaged[0].Dockey。在执行此操作之前,验证Messaged数组是否包含您尝试访问的成员。

!this.eventdata.Messaged[0]

你的最终状况应该是

if (!this.eventdata || !this.eventdata.Messaged || this.eventdata.Messaged.length === 0 || !this.eventdata.Messaged[0] || !this.eventdata.Messaged[0].Dockey) {