-
-
Save codepope/8847630 to your computer and use it in GitHub Desktop.
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 | |
} | |
} | |
); | |
} | |
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!
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.
Line 14. Tried after installing mqtt and mongodb from npm. It looks like a db is never passed to the function.