IMD SolutionComputing LibraryShop main store

How-to

Saving the payload_raw value from MQTT in Node-RED to MySQL

Edge computing and IIoT Published 7 min read

Short answer

The subscription rg186/devices/thingsnode/# already matches the uplink topic rg186/devices/thingsnode/up, so new readings reach the flow on their own. The empty write has two causes: the body is parsed nowhere before the function reads payload_raw, and the INSERT concatenates the value while a parameter array sits unused for lack of a ? placeholder. Parse the body, read msg.payload.payload_raw, bind it, deploy.

On this page
  1. Check that the subscription matches the publishing topic
  2. Parse the payload before reading a field
  3. Read payload_raw and payload_fields from the uplink
  4. Worked example: one Things Node uplink with counter 3792
  5. Bind the value with a placeholder instead of concatenation
  6. Verify that each new uplink inserts a row
  7. Questions asked

Your subscription is not the problem: the filter rg186/devices/thingsnode/# already matches the uplink topic rg186/devices/thingsnode/up, and once the flow is deployed every new reading runs through to MySQL on its own, with no polling loop. The two real faults are in the function. The body that arrives from the broker is still text or bytes until you parse it, so reading payload_raw straight off msg.payload returns nothing. And the INSERT concatenates the value into the SQL text while also supplying a parameter array the statement never uses, because the query has no ? placeholder to bind it to. Parse the body, read msg.payload.payload_raw, bind the value through the placeholder, and take decoded measurements from payload_fields where you need them.

Check that the subscription matches the publishing topic #

In an MQTT topic filter, + matches exactly one level and # matches the parent level plus every level below it. That makes rg186/devices/thingsnode/# a valid subscription for the uplink topic this device publishes. The narrower filter you tested from the command line, +/devices/+/up, matches the same messages: one application id at the first level, one device id at the second, uplink direction.

Item Value in this setup What it tells you
Published uplink topic rg186/devices/thingsnode/up the topic the device's messages arrive on
Flow subscription rg186/devices/thingsnode/# matches the uplink topic and every child topic below it
Narrower option rg186/devices/thingsnode/up also matches; only excludes sibling child topics
Command-line check filter +/devices/+/up matches any application id and any device id, uplink only

Decision: leave the subscription as it is. Narrowing it to the uplink topic is tidy, but topic matching and JSON parsing are separate checks — changing the filter cannot fix a field that reads empty.

Parse the payload before reading a field #

Connect a Debug node directly to the MQTT input. The Debug node displays msg.payload by default and can be configured to show any property or the whole message, so set one instance to show the complete message and watch a live uplink. Then classify what the payload actually is:

What the debug shows What it means What to do
An object with payload_raw inside the body was already parsed read the field directly
Text that starts with { the body is still serialized JSON parse it before property access
A buffer, shown as raw bytes the body arrived undecoded convert to text, then parse
A parse error in the sidebar the body is not valid JSON stop the write and inspect the body and msg.topic

The MQTT input node's output setting decides which of these you get: it can deliver the body as a buffer, as text, or as an object it has already parsed. Rather than depending on that setting, normalize inside the function — the version below accepts all three. A Change node with an expression against the payload property can also pull a single field out, but the function keeps the type checks, the parse and the extraction in one place you can read.

Once the body is an object, fields follow plain nesting. payload_raw and payload_fields are siblings at the top of the message, the decoded measurements sit inside payload_fields, and the timestamps sit inside metadata.

Value you want Path once the body is an object This uplink's example
Encoded raw payload msg.payload.payload_raw DiwA2wcO
Decoded measurement object msg.payload.payload_fields carries battery, event, light and temperature
One measurement msg.payload.payload_fields.temperature 18.06
Uplink time msg.payload.metadata.time the ISO timestamp string in the message

payload_raw is the Base64 text of what the device transmitted over the radio, so storing that exact string needs no decoding at all. Turning it back into measurements needs the device's payload layout, and Base64 decoding alone does not give you field boundaries, scaling or units — those come from the device's decoder definition, which is also where the unit for a value like the temperature reading comes from. Where the decoder has already run, payload_fields carries the finished values, and a guide on extracting TTN uplink metadata with ttn-device nodes shows how to pull the remaining uplink fields without hand-written paths.

Inputs, taken from the uplink message as published in this setup and from the table definition: payload_raw is the 8-character string DiwA2wcO; the message counter is 3792; the destination is table LoraTest, column Bettery; the statement under repair is INSERT INTO LoraTest (Bettery) VALUES (?).

The rule, in words: Base64 packs 3 bytes of raw data into 4 characters; each ? placeholder consumes exactly one element of the parameter array; a text column storing the string must be at least as wide as the string.

The arithmetic, written out:

  • Raw payload size: 8 characters ÷ 4 characters per group = 2 groups; 2 groups × 3 bytes per group = 6 bytes of radio payload behind DiwA2wcO.
  • Binding check: the statement contains 1 placeholder; the parameter array [data.payload_raw] holds 1 element; 1 placeholder binds 1 element, with nothing left unused.
  • Column width: the stored string is 8 characters, so any character column of at least 8 characters holds it.

Result: the INSERT writes one row into LoraTest with Bettery set to DiwA2wcO, taken from that uplink.

Decision: store the string as-is. Six bytes with no field layout cannot be turned into measurements by decoding alone, so do not decode blind — read the finished values from payload_fields instead. And because a column named Bettery looks like a home for a numeric battery reading while the value it would receive here is an 8-character text string, check the column's type before the first deploy: a mismatch means either a rejection at the MySQL node or a string parked where a number belongs.

Bind the value with a placeholder instead of concatenation #

The MySQL node's documented contract takes the SQL text in msg.topic and, when the statement contains ? placeholders, substitutes the elements of the msg.payload array in order. The original function puts the value in the array but also glues it into the SQL string; with no ? in the statement, the array is ignored and the concatenation is what executes. Replace both faults with one function:

var data = msg.payload;
try {
    if (Buffer.isBuffer(data)) {
        data = data.toString();
    }
    if (typeof data === "string") {
        data = JSON.parse(data);
    }
} catch (e) {
    node.error("Uplink body is not valid JSON", msg);
    return null;
}
if (!data || typeof data.payload_raw !== "string") {
    node.error("payload_raw is missing or is not a string", msg);
    return null;
}
msg.topic = "INSERT INTO LoraTest (Bettery) VALUES (?)";
msg.payload = [data.payload_raw];
return msg;

This also drops the original's undeclared intermediate assignment: use one declared variable and no loose copies. LoraTest and Bettery are spelled here exactly as they were created in this setup — if the column name is really a typo for a battery column, fix the statement and the schema together, because the MySQL node rejects a column that does not exist. String concatenation into SQL is an injection hazard as well, and it breaks silently the first time a value carries a quote character; the placeholder removes both risks at once. The same binding pattern is the one that saves Node-RED OPC UA values to MySQL through a template insert on a different transport. Note that this function replaces msg.topic with the SQL text, so a Debug node placed after it shows the query and the array, not the MQTT topic.

  1. Deploy the flow.
  2. Keep one Debug node on the MQTT input showing the complete message and one after the function showing what leaves it; each Debug node can be set to display a single property or the whole message.
  3. Add a Catch node scoped to the function and the MySQL node, so a failed parse or a rejected INSERT surfaces in the sidebar instead of disappearing.
  4. Wait for the next real uplink. Every message the MQTT input receives passes through the wired nodes once, with no polling or trigger node needed.
  5. Query LoraTest and compare the newest row against the counter value in that uplink's message.
  6. If the write fails with a connection refusal rather than a parse error, the flow is fine and the fault is database reachability — fixing ECONNREFUSED when Node-RED connects to a remote SQL database walks that failure on its own.

End state: subscription unchanged, parsing normalized in the function, one ? placeholder bound to one array element, and a row inserted for every uplink without any further manual step.

Questions asked

How do I store a decoded measurement such as the temperature in its own column?

Read msg.payload.payload_fields.temperature in the same function, add a second ? to the INSERT, list the extra column beside Bettery in the column list, and append the value to the parameter array in the same order as the placeholders. Take the unit from the device decoder definition rather than assuming one from the field name.

Why does the debug panel show the SQL statement instead of the sensor value?

The function overwrites msg.topic with the INSERT text and msg.payload with the parameter array, so a Debug node downstream displays the query and its bound values. Keep one Debug node upstream of the function to watch the incoming uplink, and the downstream one for the SQL.

Why did one physical reading insert two rows?

MQTT redelivers: a retained message is sent again on every reconnect or fresh subscription, and a quality-of-service retry can replay an older message after a lost acknowledgement. Node-RED processes each message it receives, so replays become duplicate rows. If duplicates matter, key rows on the counter field in the uplink, which the device increments with every transmission, and check its reset and rollover behavior.

Does the ? placeholder work with every database node?

The SQL-in-msg.topic with a values array in msg.payload is the documented interface of the standard MySQL node. Other database nodes expose their own parameter property or a query object instead, so check the node's help panel before reusing the pattern. The contract belongs to the node, not to SQL itself.

Keep reading

  • How-to

    Configuring OPC UA to MySQL writes with a Template node

    A Template node between the OPC UA client and the MySQL node renders the counter into an INSERT statement on the topic property, the place the standard MySQL node looks for its query. The payload must carry only the scalar value, and the Now function stamps database execution time, not the OPC UA source timestamp.

    Edge computing and IIoT

  • Troubleshooting

    Fix ECONNREFUSED when Node-RED connects to a remote SQL database

    ECONNREFUSED 127.0.0.1:3306 means the MySQL node dialed loopback on the machine running Node-RED, so the database computer was never contacted. Put the database computer's LAN address in the node's Host field, confirm MariaDB listens on that interface with TCP 3306 open, and create the account with the edge device's address as its host part.

    Edge computing and IIoT

  • Comparison

    Historian-like data logging on a restricted edge network

    On a restricted plant network the approved destination decides the architecture: write directly from Node-RED to the database when that connection is approved, publish MQTT and land it in InfluxDB with Telegraf when only a broker is approved, and capture to local files when nothing outbound is allowed. Whatever the path, prove store-and-forward with an outage test sized from your tag count and write period.

    Edge computing and IIoT