{"id":17839,"library":"node-red-node-mongodb","title":"Node-RED MongoDB Node","description":"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.","status":"active","version":"0.2.5","language":"javascript","source_language":"en","source_url":"https://github.com/node-red/node-red-nodes/tree/master/storage/mongodb","tags":["javascript","node-red","mongodb"],"install":[{"cmd":"npm install node-red-node-mongodb","lang":"bash","label":"npm"},{"cmd":"yarn add node-red-node-mongodb","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-red-node-mongodb","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime dependency for interacting with the MongoDB server.","package":"mongodb","optional":false}],"imports":[],"quickstart":{"code":"// This quickstart demonstrates direct MongoDB interaction\n// using the 'mongodb' driver, which is what the Node-RED node\n// 'node-red-node-mongodb' ultimately uses under the hood.\n// The Node-RED node provides a visual, flow-based interface\n// to these operations.\n//\n// To use the Node-RED node:\n// 1. Ensure Node.js and npm are installed.\n// 2. Install Node-RED globally: npm install -g node-red\n// 3. Start Node-RED: node-red\n// 4. Navigate to the Node-RED user directory (typically ~/.node-red).\n// 5. Install the MongoDB node: npm install node-red-node-mongodb\n// 6. Restart Node-RED and find the MongoDB nodes in the palette to build flows.\n\nimport { MongoClient } from 'mongodb';\n\nasync function runMongoExample() {\n  // For actual Node-RED use, connection string would be in node config.\n  const uri = process.env.MONGO_URI ?? 'mongodb://localhost:27017';\n  const dbName = 'nodeRedExampleDB';\n  const collectionName = 'sensorData';\n\n  const client = new MongoClient(uri);\n\n  try {\n    await client.connect();\n    console.log(\"Connected successfully to MongoDB server\");\n    const db = client.db(dbName);\n    const collection = db.collection(collectionName);\n\n    const dataToInsert = {\n      timestamp: new Date(),\n      temperature: Math.random() * 30 + 15, // Random temp between 15-45\n      humidity: Math.random() * 40 + 50,    // Random humidity between 50-90\n      location: 'serverRoom01',\n      _id: `sensor_${Date.now()}` // Example for handling _id\n    };\n\n    // Insert a document (equivalent to Node-RED 'out' node with 'Insert' operator)\n    const insertResult = await collection.insertOne(dataToInsert);\n    console.log(`Document inserted with _id: ${insertResult.insertedId}`);\n\n    // Find documents (equivalent to Node-RED 'in' node with 'Find' operator)\n    const query = { location: 'serverRoom01' };\n    const foundDocuments = await collection.find(query).limit(5).toArray();\n    console.log(`Found ${foundDocuments.length} documents:`);\n    foundDocuments.forEach(doc => console.log(doc));\n\n    // Update a document (equivalent to Node-RED 'out' node with 'Update' operator)\n    const updateResult = await collection.updateOne(\n        { _id: dataToInsert._id },\n        { $set: { temperature: 25.5, status: 'updated' } }\n    );\n    console.log(`Matched ${updateResult.matchedCount} docs, modified ${updateResult.modifiedCount} docs.`);\n\n  } catch (err) {\n    console.error(\"Failed to connect or perform MongoDB operations:\", err);\n  } finally {\n    await client.close();\n    console.log(\"MongoDB connection closed.\");\n  }\n}\n\nrunMongoExample();","lang":"javascript","description":"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."},"warnings":[{"fix":"Run `npm install node-red-node-mongodb` in your Node-RED user directory (typically `~/.node-red`).","message":"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.","severity":"breaking","affected_versions":">=0.10.8 of Node-RED core"},{"fix":"Remove any older `mongodb` client packages by running `npm remove mongodb` in your Node-RED user directory before installing `node-red-node-mongodb`.","message":"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.","severity":"breaking","affected_versions":">=0.1.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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.","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.","error":"TypeError: MongoClient.connect is not a function"},{"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.","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.","error":"MongoDB is inserting new documents instead of updating existing ones."},{"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.","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).","error":"MongoNetworkError: failed to connect to server [hostname:port] on first connect [Error: connect ECONNREFUSED ...]"},{"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.","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.","error":"Authentication failed."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}