"TypeError: Cannot read property 'decoded_payload' of undefined"

When I inject code:

{
    "received_at": "2022-02-27T23:45:18.013631675Z",
    "uplink_message": {
        "session_key_id": "AX88sOZsNTkoN5rZ+Rzx/Q==",
        "f_port": 1,
        "f_cnt": 80,
        "frm_payload": "SGVsbG8sIHdvcmxkIQ==",
        "decoded_payload": {
            "degreesC": 20.20263671875,
            "humidity": 38.1103515625
        }
    }
}

into function node:

var thing = [{
    degreesC: msg.payload.uplink_message.decoded_payload.degreesC,
    humidity: msg.payload.uplink_message.decoded_payload.humidity,
}]
msg.payload = thing;
return msg;

I get

2/27/2022, 7:06:04 PMnode: a99be1c0d3d3695d
msg.payload : array[1]
array[1]
0: object
degreesC: 20.20263671875
humidity: 38.1103515625

So everything works fine. But when I feed the following (basically the same) MQTT payload into the same function:

{
    "end_device_ids": {
        "device_id": "eui-70b3d57ed004d388",
        "application_ids": {
            "application_id": "mqtt-rpi3b"
        },
        "dev_eui": "70B3D57ED004D388",
        "join_eui": "0000000000000000",
        "dev_addr": "260C0875"
    },
    "correlation_ids": [
        "as:up:01FWYS5ZNTV0C25QZG3CZYW2WY",
        "gs:conn:01FWY7ADE93XZZ8A72N1EHDH2S",
        "gs:up:host:01FWY7ADJXWZWYHXHR5852CGS8",
        "gs:uplink:01FWYS5ZF1JRJDHCP9SDDMN718",
        "ns:uplink:01FWYS5ZF4TDHF5473B8CBK29V",
        "rpc:/ttn.lorawan.v3.GsNs/HandleUplink:01FWYS5ZF4744HNW8ZJ25RDB26",
        "rpc:/ttn.lorawan.v3.NsAs/HandleUplink:01FWYS5ZNS2ZXRQ5WT1B7GV9VX"
    ],
    "received_at": "2022-02-27T23:45:18.013631675Z",
    "uplink_message": {
        "session_key_id": "AX88sOZsNTkoN5rZ+Rzx/Q==",
        "f_port": 1,
        "f_cnt": 80,
        "frm_payload": "SGVsbG8sIHdvcmxkIQ==",
        "decoded_payload": {
            "degreesC": 20.20263671875,
            "humidity": 38.1103515625
        }
    }
}

I get:

2/27/2022, 7:05:34 PMnode: Test
function : (error)
"TypeError: Cannot read property 'decoded_payload' of undefined"

I'm just learning this stuff, so be kind.

From what you have shown us, it seems your code and data are fine but obviously something else is going on. Lets add some debug messages to your function...


if(!msg.payload.uplink_message) {
  node.warn(["this msg does not have '.payload.uplink_message' - look closely at its content", msg]);
}

var thing = [{
    degreesC: msg.payload.uplink_message.decoded_payload.degreesC,
    humidity: msg.payload.uplink_message.decoded_payload.humidity,
}]
msg.payload = thing;
return msg;

I needed to "Always convert to JavaScript Object' by adding a JSON node before the function.
Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.