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 ショーコレクション