viết code node.js để kết nối mqtt broker tới mongodb
- User
viết code node.js để kết nối mqtt broker tới mongodb
- Assistant
Để kết nối tới MQTT broker và lưu dữ liệu vào MongoDB, ta cần sử dụng các module sau đây:
mqttđể kết nối tới broker,mongodbđể thao tác với cơ sở dữ liệu.Ví dụ, ta muốn lưu trữ tất cả các message đến từ MQTT topic
/devicesvào collectiondevicedatatrong MongoDB databasemydb.const mqtt = require('mqtt'); const MongoClient = require('mongodb').MongoClient; // MQTT broker config const brokerUrl = 'mqtt://broker.mqtt.com'; const topic = '/devices'; // MongoDB config const mongoUrl = 'mongodb://localhost:27017/mydb'; const mongoCollection = 'devicedata'; // MQTT client const mqttClient = mqtt.connect(brokerUrl); // MongoDB client MongoClient.connect(mongoUrl, function(err, client) { if(err) throw err; console.log('Connected to MongoDB'); const db = client.db(); // MQTT subscription mqttClient.on('connect', function () { console.log('Connected to MQTT broker'); mqttClient.subscribe(topic); }); // MQTT message handler mqttClient.on('message', function (topic, message) { console.log(`Received MQTT message on ${topic}: ${message.toString()}`); // convert message to JSON const data = JSON.parse(message.toString()); // insert data into MongoDB db.collection(mongoCollection).insertOne(data, function(err, res) { if(err) throw err; console.log('Inserted data into MongoDB'); }); }); });Chú ý rằng ta chuyển đổi message từ dạng string sang JSON object bằng cách sử dụng
JSON.parse(), và sử dụnginsertOne()method để thêm dữ liệu vào collection trong MongoDB.Lưu ý, thay thế
brokerUrlvàmongoUrlvới các giá trị tương ứng của bạn. Chạy chương trình và nó sẽ bắt đầu kết nối tới MQTT broker và MongoDB. Sau đó, mỗi message nhận được từ MQTT broker trên topic/devicessẽ được chèn vào collectiondevicedatacủa MongoDB.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.