2017-06-26 11 views
0

MQTTブローカーからMongodbにデータを保存しようとしています。次のコードを使用します。MQTTを使用してMongodbにデータを挿入できません

var mqtt = require('mqtt'); //includes mqtt server 
var mongodb = require('mongodb'); // includes mongoDB 
var mongodbClient = mongodb.MongoClient; //initialises the mongoDB client 
var mongodbURI = 'mongodb://localhost:27017/WheelSenseHat'; 
var deviceRoot = "iot-lab/wheel/sensehat/"; 
var collection,client; 

mongodbClient.connect(mongodbURI, setupCollection); 

function setupCollection(err, db) { 
    if(err) 
throw err; 
    collection=db.collection("WheelData"); 
    client=mqtt.connect({ host: 'iot.eclipse.org', port: 1883 }); 
    client.subscribe(deviceRoot+"+"); //subscribing to the topic name 
    client.on('message', insertEvent); //inserting the event 

} 

//function that displays the data in the MongoDataBase 
function insertEvent(topic,message) { 
    var key=topic.replace(deviceRoot,''); 
    collection.update(
    { _id:key }, 
    { $push: { events: { event: { value:message, when:new Date() } } } }, 
    { upsert:true }, 

    function(err,docs) { 
    if(err) { 
     console.log("Insert fail")// Improve error handling  
    } 
} 

); 

} 

ただし、データはMongoDBに保存されません。出力は以下の通り:

ショーDBS 管理0.000ギガバイト ローカル0.000ギガバイト 使用 は、あなたのプログラムでもMQTTメッセージを受信して​​いるWheelSenseHat ショーコレクション

答えて

1

DBへの切り替えWheelSenseHat? をinsertEvent()関数に入れて、それが呼び出されているかどうかを確認してください。あなたの購読はiot-lab/wheel/sensehat/+に翻訳されます。iot-lab/wheel/sensehat/data1のようなMQTTメッセージと一致しますが、ではありません。「+」は「レベル」に一致し、「#」は何でも一致します。受信MQTTメッセージに 'sensehat'を超えるレベルが複数ある場合、プログラムはメッセージを受け取りません。したがって、データベースにはレコードがありません。

関連する問題