Function node to keep same topic

hi so i want to do something relly basic change a string message that comes from mqtt from 0 to 1 and from 1 to 0 i tried to do it with a change node but i put both options inside but it only does one and not both

so itried the funktion node and it works perfectly but i lose the topic which is really important ,ho do i keep the same topic?

if (msg.payload === "1") {
   msg = { payload:"0" };
} else {
   msg = { payload:"1" };
return msg;

In your code you are creating a whole new message and returning it.

It's a better habit to reuse the msg object you've been given - as that then preserves the other properties:

if (msg.payload === "1") {
   msg.payload = "0";
} else {
   msg.payload = "1";
return msg;

hi thanks for your fast response cause i am new with java script and learning now can show me what you mean ?

Hi @Giaitzoglou

I provided exactly the code you could use in my reply.

Where you were doing:

msg = { payload:"0" };

I changed it to:

msg.payload = "0";

In your code, you were assigning msg to a new object - so it lost all of the other properties on the message.
In my code, we keep the existing msg object and just update its payload.

ohhh sorry i unsderstand now can i ask you why it didnt work in the change node ?

The Change node applies each rule you set in the order you list them.

This means:

  • if payload is 1, the first rule does nothing, the second rule changes it to a 0. That is good.
  • if payload is 0, the first rule will change it to a 1. The second rule then finds that 1 and changes it back to a 0. That is bad.

thanks a lot for your help

Try using a intermediary value in the change node;



1 Like

This is one of the few cases where I would use JSONata



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