Node-RED MongoDB Node

raw JSON →
0.2.5 verified Thu Apr 23 auth: no javascript

This package provides Node-RED nodes for interacting with MongoDB databases, enabling users to store and retrieve data within their Node-RED flows. It abstracts the complexities of the MongoDB driver, allowing operations like `find`, `count`, `aggregate`, `save`, `insert`, `update`, and `remove` via message properties (`msg.payload`, `msg.query`, `msg.collection`). Originally part of Node-RED core, it was spun out as a separate installable package from Node-RED v0.10.8 onwards. The current stable version is 0.8.0, with a release cadence that seems to follow major Node-RED or MongoDB driver updates, marked by 'Milestone Release' entries. Key differentiators include its tight integration with the Node-RED flow paradigm and simplified database interactions for IoT and data processing scenarios. It requires a running MongoDB server and depends on a MongoDB client package version 3.6.3 or newer.

error TypeError: MongoClient.connect is not a function
cause An older, incompatible version of the `mongodb` client package (e.g., v2) is present in the Node-RED environment, conflicting with the v3+ API expected by this node.
fix
In your Node-RED user directory (~/.node-red), run npm remove mongodb followed by npm install node-red-node-mongodb to ensure a compatible client version is installed.
error MongoDB is inserting new documents instead of updating existing ones.
cause The `_id` property is not consistently provided or is missing for update/save operations, causing MongoDB to treat the incoming data as a new document.
fix
In a Node-RED function node prior to the MongoDB 'out' node, set msg.payload._id (if sending msg.payload) or msg._id (if sending msg object) to a unique and consistent identifier for the document you intend to update or save idempotently.
error MongoNetworkError: failed to connect to server [hostname:port] on first connect [Error: connect ECONNREFUSED ...]
cause The MongoDB server is not running, is unreachable from the Node-RED host, or the connection string in the node's configuration is incorrect (e.g., wrong hostname, port).
fix
Verify that your MongoDB server is running and accessible from the Node-RED machine. Double-check the connection string in the MongoDB node's configuration within the Node-RED editor for correct hostname, port, and any necessary credentials.
error Authentication failed.
cause The provided username or password in the MongoDB connection string or node configuration is incorrect, or the user lacks the necessary permissions for the database.
fix
Ensure the username and password configured for the MongoDB connection are correct and have the appropriate read/write access to the target database and collections.
breaking This node was moved out of Node-RED core as of Node-RED v0.10.8. Existing flows expecting it to be pre-installed will fail unless the package is explicitly installed.
fix Run `npm install node-red-node-mongodb` in your Node-RED user directory (typically `~/.node-red`).
breaking This package requires a MongoDB client package version 3.6.3 or newer. If an older (e.g., v2) `mongodb` client is present in your Node-RED environment, it may cause compatibility issues.
fix Remove any older `mongodb` client packages by running `npm remove mongodb` in your Node-RED user directory before installing `node-red-node-mongodb`.
gotcha When using 'Save' or 'Insert' operations, MongoDB automatically creates an `_id` property if one is not provided. Repeatedly sending the same `msg` without a consistent `_id` will result in multiple new database entries instead of overwriting existing ones.
fix If idempotent behavior is desired (i.e., overwriting existing documents), ensure `msg._id` is set to a constant or derived unique identifier in a preceding function node before the message reaches the MongoDB output node.
gotcha For 'Remove' operations, providing an empty `msg.payload` as the query will delete *all* documents in the specified collection. This can lead to unintended data loss.
fix Always provide a specific `msg.payload` query object for 'Remove' operations unless a complete collection wipe is explicitly intended. Implement confirmation steps in your Node-RED flow for critical delete operations.
gotcha This package is a Node-RED node, not a standalone JavaScript library meant for direct `import` or `require()` statements in a typical Node.js application. Its functionality is exposed and configured within the Node-RED flow editor.
fix To use this package, install it within your Node-RED environment (e.g., `npm install node-red-node-mongodb` in `~/.node-red`) and then drag and configure the MongoDB nodes from the Node-RED palette.
npm install node-red-node-mongodb
yarn add node-red-node-mongodb
pnpm add node-red-node-mongodb

Demonstrates programmatic MongoDB interaction using the underlying driver, paralleling the operations provided by the Node-RED node, and provides installation steps for the Node-RED package itself.

// This quickstart demonstrates direct MongoDB interaction
// using the 'mongodb' driver, which is what the Node-RED node
// 'node-red-node-mongodb' ultimately uses under the hood.
// The Node-RED node provides a visual, flow-based interface
// to these operations.
//
// To use the Node-RED node:
// 1. Ensure Node.js and npm are installed.
// 2. Install Node-RED globally: npm install -g node-red
// 3. Start Node-RED: node-red
// 4. Navigate to the Node-RED user directory (typically ~/.node-red).
// 5. Install the MongoDB node: npm install node-red-node-mongodb
// 6. Restart Node-RED and find the MongoDB nodes in the palette to build flows.

import { MongoClient } from 'mongodb';

async function runMongoExample() {
  // For actual Node-RED use, connection string would be in node config.
  const uri = process.env.MONGO_URI ?? 'mongodb://localhost:27017';
  const dbName = 'nodeRedExampleDB';
  const collectionName = 'sensorData';

  const client = new MongoClient(uri);

  try {
    await client.connect();
    console.log("Connected successfully to MongoDB server");
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    const dataToInsert = {
      timestamp: new Date(),
      temperature: Math.random() * 30 + 15, // Random temp between 15-45
      humidity: Math.random() * 40 + 50,    // Random humidity between 50-90
      location: 'serverRoom01',
      _id: `sensor_${Date.now()}` // Example for handling _id
    };

    // Insert a document (equivalent to Node-RED 'out' node with 'Insert' operator)
    const insertResult = await collection.insertOne(dataToInsert);
    console.log(`Document inserted with _id: ${insertResult.insertedId}`);

    // Find documents (equivalent to Node-RED 'in' node with 'Find' operator)
    const query = { location: 'serverRoom01' };
    const foundDocuments = await collection.find(query).limit(5).toArray();
    console.log(`Found ${foundDocuments.length} documents:`);
    foundDocuments.forEach(doc => console.log(doc));

    // Update a document (equivalent to Node-RED 'out' node with 'Update' operator)
    const updateResult = await collection.updateOne(
        { _id: dataToInsert._id },
        { $set: { temperature: 25.5, status: 'updated' } }
    );
    console.log(`Matched ${updateResult.matchedCount} docs, modified ${updateResult.modifiedCount} docs.`);

  } catch (err) {
    console.error("Failed to connect or perform MongoDB operations:", err);
  } finally {
    await client.close();
    console.log("MongoDB connection closed.");
  }
}

runMongoExample();