Smithy
Smithy

Reputation: 791

How to combine two SQLite queries using Node-RED

I have two sql queries that i want to run against the same database. I want to combine the results of the two queries into a single object, so that i can use it in a html template further down the road.

Running them both separately works as expected and returns an object with the correct data from the database.

Below is a screenshot of the Node-RED flow. Screenshot of node red flow

In my combine function i have tried the following code but it just gives me two separate arrays, that contain one object:

var myArray = [];
var ob = {};

for(var i = 0; i < msg.payload.length; i++){
    ob = msg.payload[i];
    myArray.push(ob);
}
msg.topic = myArray;
return msg

I believe this is because the queries are executed one after the other. Is there a way to execute them at the same time and store the result?

Upvotes: 0

Views: 2328

Answers (2)

SteveR
SteveR

Reputation: 1131

It is a common misconception that wiring two paths into one function node will somehow combine the two msg objects -- which are guaranteed to arrive at different times due to the single-threaded nodejs flow processor...

There is no benefit to splitting your injected event into two parallel paths that need to be joined later before they can be processed. Instead, it's easier to trigger the first query (e.g. getSchedules), wire it to a change node where you move the output results to something like msg.schedules, and finally wire the change node to the second query (e.g. getExams). If the query nodes are well-behaved, the second one should put the exam results in msg.payload without touching the incoming msg.schedules data.

At this point, you should have a single msg object with both sets of data -- so no combine function is needed. And although you have 2 query nodes in series, they can use the same config node, so they share a connection to the database.

Upvotes: 1

hardillb
hardillb

Reputation: 59866

Replace your combine function node with a join node set it to join on when it receives 2 messages and if you play around with the options it should be able to join the 2 arrays

Upvotes: 1

Related Questions