[solved] Publishing dynamic MQTT topics

Hello,
I have an input node that gives me a JSON with lots of keys and values. I'm able to extract the "deveui" value and the "payload" value. I'd like to publish this as a new MQTT message that is has a topic name of the value for "deveui" and a message that is the value for "payload".

I'm able to extract the two individually. But I'm unsure about how to create a new payload as input to the MQTT publish node so that the MQTT node takes dynamic topic and payloads.

I hope this image explains is well enough.

I tried something like this for the input function to the MQTT node, but it's incorrect.

var mynewout;
mytopic = msg.deveui;
mypayload = msg.payload;

mynewout.topic = mytopic;
mynewout.payload = mypayload;

return mynewout;

Edit: Closing the loop in case someone else runs into this, I initialize the new variable to msg and the MQTT publishes work correctly now. So like this

var mynewout=msg;
mytopic = msg.deveui;
mypayload = msg.payload;

mynewout.topic = mytopic;
mynewout.payload = mypayload;
msg.topic = mytopic;
msg.payload = mypayload;
return msg;

How about

msg.topic = msg.deveui;
return msg;

Also make sure you mqtt out node has no topic set as it'll override the incoming topic.

Yes, I left the MQTT node's topic blank, so it should take on the input node's topic. Trying what you wrote, I still get the same error msg, " cannot set property 'topic'"

Do you mean you have a Function node containing only those two lines and you see that error? Are you sure it is the function node that is generating the error?

Hi @Eric

The problem with the function code you have is that you declare mynewout as a variable, but you don't initialise it to anything - it is undefined. That means you cannot set the topic and payload properties and why you get the error message you do - it literally cannot set the topic property of an undefined value.

The suggestion from @nlecaude will have the same end result - returning a message with the same payload, but the topic now set to whatever msg.deveui was. This is generally a better approach than creating a new object - it will preserve any other msg properties.

Thanks. Initializing it solves the issue, and now I'm getting the correct MQTT pubs.