I'm a newbee at Node-Red and I'd like to collect information from my MQTT and push it to my database.
Initially I subscribe for a branch of topics (Devices/+) and receive around 50 MQTT messages. Now I'd like to combine them into one single object and store it into database at once instead of 50 different queries.
Is there a handsome way (without Flow variables) to do so?
Do you mean store into an array at Flow level variable?
Looking to this option but can't understand it completely. It seems that I have to add a function that will modify MQTT msg into a way it can be received by Join.
var val = msg.payload; // get the value
var key = msg.topic; //get the topic
var mqttData= flow.get("mqttData") || {}; //get the store object
mqttData[key] = val; // add/update the value
flow.set("mqttData", mqttData); // save to flow context
I saw also an example with Batch, that can wait for a number of messages and only then pass them to Join. But this is not a good option due to potential lack of some topics.
I assume that I should push it to DB as soon as I get all the values or timeout passed. Your note makes sense. If some of the topics is missed then I can wait for it until end of the world (or timeout).
As you see as DB I use InfluxDB that is not relational DB and is designed for storing sequences of data. And it is a really matter of the schema design. Here I have two options:
Store with narrow sequences (as at yours example). In that case I need to use different Measurements (Tables) to store different nature of data.
Use wide sequences (as I planned to do initially) where I have a number of Tags (qualifiers, keys) that will help me to select and combine data.
Option 2 is as it is described in the most examples at InfluxDB. Option 1 looks more reasonable in terms to processing of MQTT events. In that case I can use one single (I hope) function that will be universal.
Let me check the Option 1 also.
Anyway combining of several objects into one is also not bad timeleisure.
Finally I came to the narrow-long table where I can distingiush the concrete types with TAGs.
And I can do a selection from # widlcard topic with SWITCH that passes to a neccesary function. The next step is to use function that will do everything inside without any switches in before.
switch (msg.topic){
case 'Dacha/pressure':
lLocation="Dacha";
lArea="Pantry";
lMeasurement="Pressure"
msg.valid=true;
break;
case 'Dacha/temp':
lLocation="Dacha";
lArea="Pantry";
lMeasurement="Temperature"
msg.valid=true;
break;
And the sequence in the DB is also anrrow. I use keys to distinguish data. Actually I don't know wheeather it is good or bed. We will se when some amount of data is stored.