IMD SolutionComputing LibraryShop main store

Troubleshooting

Passing an MQTT badge identifier as a MongoDB find filter in Node-RED

Edge computing and IIoT Published 6 min read

Short answer

The mongodb in node returns every document because the function forwards the bare badge identifier, which gives find no field to match. Forward a filter object with badgeID set to the identifier, and add msg.projection excluding _id and keeping tempValue. Match the stored text type, and confirm 127.0.0.1:27017 is reachable from the Node-RED runtime's own namespace.

On this page
  1. Why a bare identifier returns every document
  2. Confirm what arrives on badgeDetected
  3. Build the filter object in the function node
  4. Worked example: five documents in, one out
  5. Match the stored type, not the displayed value
  6. Return only tempValue with a projection
  7. Check where 127.0.0.1 actually points
  8. Sort the symptom to the layer
  9. Questions asked

The MongoDB node returns every document in the collection because the function node forwards the bare badge identifier, and a bare string gives the find operation no field to match. The fix is one line: send the identifier inside a filter object, msg.payload = { badgeID: sensorMeasurement.badgeID };, and attach msg.projection = { '_id': 0, 'tempValue': 1 }; to the same message so only the temperature comes back. This article works through the flow as given — topic badgeDetected, database iotsuiteuser, collection ProfileDB — and proves the result against its five stored documents.

Why a bare identifier returns every document #

The mongodb in node reads its query from msg.payload. In the find operation, each field-and-value pair in that object is one equality test, and an object with no pairs matches every document. The failing function assigns the parsed value straight to the payload:

sensorMeasurement = JSON.parse(msg.payload);
msg.payload = sensorMeasurement.badgeID;
return msg;

The database node now receives the text 69d65035, a value with no field name. With no condition to evaluate, find matches the entire collection, and the Debug node — set to show payload[0].tempValue — prints the first record's temperature rather than the one you asked for. An empty object behaves the same way, so an error path that falls through to an unfiltered query hides the fault instead of surfacing it.

Confirm what arrives on badgeDetected #

MQTT carries the message body and nothing more; it never converts a badge into a database condition. Before touching the query, prove what the subscriber actually receives:

  1. Wire a Debug node directly to the mqtt in node and set it to output the complete message.
  2. Present the badge to the reader and read the body that arrives on badgeDetected.
  3. Confirm the body is valid JSON and carries badgeID set to the identifier you intend to look up.
  4. Decide the representation. Node-RED's message guidance is explicit that a property holding a JSON string must be parsed to its JavaScript object before its fields can be read; with the subscriber left at its default, the body arrives as text and JSON.parse is required. If the node is configured to decode JSON itself, msg.payload is already an object and JSON.parse(msg.payload) fails on it.
  5. Guard the parse: a malformed body or a missing badgeID must stop the message there, not fall through to an unfiltered query that dumps the collection.

Only when the Debug node shows the intended identifier in a known representation is the query function worth testing.

Build the filter object in the function node #

Replace the assignment with an object that names the field:

var sensorMeasurement = JSON.parse(msg.payload);
msg.payload = { badgeID: sensorMeasurement.badgeID };
return msg;

sensorMeasurement is the parsed JSON body, an object; msg.payload becomes a query object carrying one equality condition on badgeID. If the check above showed the payload already decoded, parse nothing and build the object from the message directly: msg.payload = { badgeID: msg.payload.badgeID };.

Worked example: five documents in, one out #

The collection stores five documents keyed by badgeID as text: "1" with tempValue 25, "2" with 28, "3" with 31, "4" with 24, and "69d65035" with 33. Run both payloads against it:

  • Bare identifier 69d65035: find receives a string, applies no field condition, and matches 5 of 5 documents. The Debug expression payload[0].tempValue reads element 0 of that array and prints 25 — plausible-looking, and wrong.
  • Filter object {"badgeID":"69d65035"}: one equality test on one field, matching 1 of 5 documents. The same expression now reads the single element and prints 33.

Five documents in, one out is the whole fix; the value at the Debug node moving from 25 to 33 is the proof. The stored unit text reads C on four records and c on one, and record "4" spells the unit field unitOfMeasurement where the rest use unitofMeasurement — none of that touches a query on badgeID, but later logic reading units must use the spelling its target record carries.

Match the stored type, not the displayed value #

Every stored badgeID is text: "1", "2", "3", "4", "69d65035". MongoDB equality is type-strict, so a reader body such as {"badgeID":12} yields the number 12, which equals no stored text value: find runs, matches nothing, and returns an empty array. Since this collection stores identifiers as text, force the incoming number into text on the filter line itself:

msg.payload = { badgeID: String(sensorMeasurement.badgeID) };

Field names are matched case-sensitively too, so badgeID must be spelled exactly as stored. The same text-versus-number trap breaks analog points delivered as quoted JSON; why a quoted MQTT JSON value fails an analog point traces that failure on the measurement side.

Return only tempValue with a projection #

Filtering selects documents; a projection selects fields inside them. The field list this database node reads is msg.projection, set on the same message the filter travels on:

var sensorMeasurement = JSON.parse(msg.payload);
msg.payload = { badgeID: sensorMeasurement.badgeID };
msg.projection = { '_id': 0, 'tempValue': 1 };
return msg;

msg.projection keeps tempValue and suppresses _id; MongoDB permits excluding the document identifier while including another field, and the find answers with one document carrying the temperature alone.

A projection cannot repair a missing filter: an unfiltered query with this projection still returns five temperatures. Put both on every query message, and treat a single-element answer with the wanted field as the pass condition.

In the mongodb in node itself, keep database iotsuiteuser, collection ProfileDB and operation find. The node's display name, ProfileDB, is only a label; the query runs against the database and collection settings, so check those two fields rather than the label.

Check where 127.0.0.1 actually points #

The database configuration addresses MongoDB at 127.0.0.1:27017, and loopback resolves inside whatever machine or network namespace the Node-RED runtime runs in. For the flow as given — Node-RED and MongoDB on the same Raspberry Pi — the loopback address is correct as written. Move Node-RED into a container and 127.0.0.1 becomes the container itself, not the Pi and not a database on any other host; point the node at the database's address on a network the two share, for example the database container's service name. Decision: same host, keep 127.0.0.1:27017; separate containers or hosts, replace it with an address the runtime can actually reach.

A connected MQTT subscription proves nothing about this path. Broker and database are separate connections from separate configuration nodes, so publish one deliberate badge and watch the Debug node downstream of find before calling the flow done.

The broker in this flow is Mosquitto's public test endpoint on port 1883 with TLS off, which is bench-grade only. Operational badge lookups belong behind a broker you control; Run a secure Mosquitto MQTT lab broker with Node-RED sets one up with TLS and access rules.

Sort the symptom to the layer #

What the Debug node shows Cause Decisive check
Every document in the collection msg.payload is a scalar or an empty object at the database node Log msg.payload immediately before the mongodb in node; it must be an object carrying badgeID
No document at all Value type or field spelling in the filter differs from the stored document Compare the filter pair against one stored document, field by field and type by type
A function error at JSON.parse The payload was already decoded, or the body is not valid JSON Check the payload type at the mqtt in output before parsing
One document with _id and the other fields The filter works but msg.projection is missing or misspelled Inspect msg.projection on the message that enters the database node

Work the table from the symptom you actually see; each row names the one layer to fix. The pass condition, restated: the function forwards { badgeID: sensorMeasurement.badgeID }, the value is a string because the documents store strings, msg.projection = { '_id': 0, 'tempValue': 1 } rides on the same message, and the Debug node shows a single record with the temperature you asked for.

Questions asked

Why does the mongodb in node return the whole collection when I pass the badge string?

The find operation reads its query from msg.payload, and a bare string carries a value but no field name. With no field to compare, the node behaves as though the query were empty, and an empty query matches every document. Only an object that names the field, with badgeID set to the identifier, narrows the result to the records that hold it.

The reader publishes badgeID as a number, so why does the fixed filter return nothing?

Because equality in MongoDB never matches a number to a string. This collection stores every badgeID as text, so a numeric identifier fails the comparison even when the digits are identical, and find returns zero documents. Convert the incoming value to text on the filter line, or change the writer so the published type and the stored type agree.

What should the Debug expression payload[0].tempValue show before and after the fix?

Before the fix, find returns all five documents, so element 0 is the first record and the expression prints its temperature, 25. After the filter object is in place the array holds one document and the same expression prints 33, the value stored for badge 69d65035. The change from 25 to 33 at that one expression is the proof that the filter is active.

Can I return more fields than tempValue with the same query?

Yes. Add every field you want to keep to msg.projection with a 1, for example the temperature and the unit field, and leave _id at 0 when you do not need the document identifier. Use the spelling each stored record carries: this collection mixes unitofMeasurement and unitOfMeasurement, so a filter on one spelling matches only the records that use it, and a projection silently omits a field whose spelling differs.

Keep reading

  • How-to

    Connect Node-RED on ctrlX CORE to a MySQL server

    Send the SQL as msg.topic to a node-red-node-mysql node: create the table once as an administrator, prove one INSERT and SELECT from Inject nodes, then route Read Datalayer values into a multi-row insert. Grant the runtime account only SELECT and INSERT on db1, match its host part to the client address the server reports, and keep a local snap's data directory on external media.

    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

  • How-to

    How to query InfluxDB over MQTT with a bridge flow

    InfluxDB does not answer queries over MQTT: it serves them over its HTTP API. Put a bridge on the edge PC — a Node-RED flow subscribed to a request topic — that maps a validated, bounded request to a query against the bucket and publishes the result to a separate response topic, so request and reply never loop.

    Edge computing and IIoT

Why a lot filter opens the wrong report template