Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

viết code node.js để kết nối mqtt broker tới mongodb

  1. User

    viết code node.js để kết nối mqtt broker tới mongodb

  2. 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 /devices vào collection devicedata trong MongoDB database mydb.

    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ụng insertOne() method để thêm dữ liệu vào collection trong MongoDB.

    Lưu ý, thay thế brokerUrl và mongoUrl vớ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 /devices sẽ được chèn vào collection devicedata của MongoDB.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.