Node-RED MongoDB Node
raw JSON →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.
Common errors
error TypeError: MongoClient.connect is not a function ↓
~/.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. ↓
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 ...] ↓
error Authentication failed. ↓
Warnings
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. ↓
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. ↓
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. ↓
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. ↓
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. ↓
Install
npm install node-red-node-mongodb yarn add node-red-node-mongodb pnpm add node-red-node-mongodb Quickstart
// 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();