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

if i run this program, its showing error TypeError: db.collection is not a function

@codepope
Copy link
Author

On what line?

@mrarmyant
Copy link

On what line?

Line 14. Tried after installing mqtt and mongodb from npm. It looks like a db is never passed to the function.

@mrarmyant
Copy link

mrarmyant commented Feb 27, 2020

After further investigation and looking at the age of this gist, looks like a version mismatch. https://stackoverflow.com/questions/47662220/db-collection-is-not-a-function-when-using-mongoclient-v3-0

It gets past this point if you used mongodb@2 on the npm install. It then errors out on createClient as not being a function, so its likely that the mqtt library has changed some too. @Shivsk007 check your versions.

Dropping mongodb to 2 and mqtt to 1 got me running with "createClient is deprecated, use connect instead" displayed.

Getting mine working with current versions, tho this gist should probably be a full on project to include a package.json or have comments with the versions to install at the top.

Not being whiny, this code is 6 years old and clearly still useful :D Thanks for the work!

@codepope
Copy link
Author

Yes, this is quite old code and the Mongo libraries changed somewhat....

Roughly where it hands over a db in setupCollextion, now it hands over a MongoDB client. You can then get the db with client.db("dbname")....

The rest should work fine though I'd write it completely differently now.

@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