How to increment msg.payload[i] in node-red

Question:

We are working on an ubuntu server, where we have installed node-red. What we want is to take data from one table on our MySQL Database, and then move it to another table.

Our flow looks like this:

enter image description here

Our ‘Select Tolerance’ node contains:

msg.topic = "SELECT * FROM Tolerance";
return msg;

Simple code, which selects data from our database. If we connect a debug node like this:

enter image description here

We then see an output looking like this:

enter image description here

We want to pick all data, so we need to go through all objects in the array and make sure to take all values and send them over to our new database table. We’re using the ‘New Tolerance’ node to do so, and ‘New Tolerance’ contains:

var i;
var secured = 1;

for (i = 0; i < msg.payload.length; i++) {
    var time_start = msg.payload[i].time_start
    var time_end = msg.payload[i].time_end
    var temperatur_lpn = msg.payload[i].temperatur_lpn
    var temperatur_rising = msg.payload[i].temperatur_rising
    var temperatur_weather = msg.payload[i].temperatur_weather
    var temp_compare_WL = msg.payload[i].temp_compare_WL
    var temp_compare_WR = msg.payload[i].temp_compare_WR

var out = "INSERT INTO Sunrise_Tolerance (time_start, time_end, temperatur_lpn, temperatur_rising, temperatur_weather, temp_compare_WL, temp_compare_WR, secured)"

out = out + " VALUES ('" + time_start + "','" + time_end + "','" + temperatur_lpn + "','" + temperatur_rising + "','" + temperatur_weather + "','" + temp_compare_WL + "','" + temp_compare_WR + "','" + secured + "');"

msg.topic = out;
return msg;
}

The problem is that we only receive the first row of data (first object in the array) and not the rest. Can anyone figure out why we dont receive all data, but only the first?

Asked By: Buster3650

||

Answers:

The problem comes the fact you have a return statement inside the for loop.

That will exit the function the first time it reaches that point – so your loop never loops.

If you want to send multiple messages you should use node.send(msg); in your for loop. The only thing to watch out for is if you call node.send with the same object multiple times, as the message is passed by reference, you would get some odd side-effects. As you only care about msg.topic in this instance, you can afford to create a new message object each time.

So, instead of the return msg statement, you could do:


for (i ... ) {
   var out = "INSERT ...";
   ...

   node.send({topic: out});
}
// Return without any arguments so no further messages are sent.
return;

Answered By: knolleary