Conditional iptus for data from MQTT to inserst into a new database table

Hello community members,
I'm not familiar with Node Red and javascript but I decided to start this challenge.
I want to collect data from a MQTT and insert the data into a new posgresql database.
This data has this structure below.

{
"value":87829,
"timestamp":1670331643594.0977,
"localTime":"2022-12-06T13:00:43.594Z",
"metadata":{
"type":"num",
"deviceId":"760FX_CF60_KBS5_TILT_SHIFT",
"aliasName":"nContadorCiclos",
"key":"nContadorCiclos",
"variable":"nContadorCiclos",
"id":"f3025051-a228-4a89-9a74-fbed4259deb7",
"variableName":"nContadorCiclos",
"task":"T_ROB1",
"module":"DynModel_Validation_760FX"
}
}

Basically with this node, I want to get the values from the data input for value, LocalTime, variableName and deviceId and return to another data called demoprod760fx. Later this new data will be inserted into a new database table.
With the same MQTT topic I will get different but similar data where objects have same name so I want to use a function node to indentify and select only what I need and avoind to get wrong values. That's why I'm considering the payload verification for taks and module because they exist only in this data type.

I started this project using another example but seems it's not correct.

Please, see below what I'm doing below with this function node.

if (msg.payload.timestamp
&& msg.payload.value
&& msg.payload.metadata
&& msg.payload.metadata.task
&& msg.payload.metadata.module
&& msg.payload.metadata.deviceId === '760FX_CF60_KBS5_TILT_SHIFT',
&& msg.payload.metadata.variableName === 'nContadorCiclos' ) {
return {
demoprod760fx: {
device_id: msg.payload.metadata.deviceId,
variable_name: msg.payload.metadata.variableName,
timestamp: msg.payload.localTime,
value: (typeof msg.payload.value === 'object') ? JSON.stringify(msg.payload.value): msg.payload.value,
}
}
}

return null;
return msg;

The most important for my project is to define the condition to get data only if the deviceId is 760FX_CF60_KBS5_TILT_SHIFT and the variableName is nContadorCiclos. The other verifications is just to ensure that I'm collecting the right value from the right data type but it's secondary and probably reduntancy.

I will appreciate if you guys can help me to set the code for this node.

If you remove the comma after ...TILT_SHIFT' then your function seems to work.

The message it creates looks like this
Untitled 3
It's slightly unusual because it doesn't have msg.payload (so a debug node showing msg.payload gives "undefined"), but if that's what you need it's no problem.

You don't really need the return null line. You could delete this and return msg. If the data does not pass your validation checks the function would just end without emitting a message.

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