Skip to content

Instantly share code, notes, and snippets.

@codepope
Created February 6, 2014 16:28
Show Gist options
  • Save codepope/8847630 to your computer and use it in GitHub Desktop.
Save codepope/8847630 to your computer and use it in GitHub Desktop.
A simple MQTT to MongoDB bridge for Node
var mqtt=require('mqtt');
var mongodb=require('mongodb');
var mongodbClient=mongodb.MongoClient;
var mongodbURI='mongodb://username:password@server.mongohq.com:port/database';
var deviceRoot="demo/device/";
var collection,client;
mongodbClient.connect(mongodbURI,setupCollection);
function setupCollection(err,db) {
if(err) throw err;
collection=db.collection("test_mqtt");
client=mqtt.createClient(1883,'localhost');
client.subscribe(deviceRoot+"+");
client.on('message', insertEvent);
}
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
}
}
);
}
@sh1vkumar
Copy link

sh1vkumar commented Feb 29, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment