Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing MongoDB outside of connection callback

I know that similar questions have been asked, but no one actually shows code that does this, they only link to pages that also don't show code.

Anyway, basically my node server receives data on a socket.io event. I want that data to go into MongoDB. The problem is that all the code examples I've seen for mongo only manipulate the db inside the MongoClient.connect callback, using the db object.

Since, I will be getting a lot of this data, I don't want to initialize over and over again.

What I need is effectively this:

MongoClient.connect(("mongodb://" + process.env.IP + ":27017/feedback"),
function(err, db) { ... });

And then later:

socket.on('data', function (data) {
    db.doStuff();
});
like image 720
Lytigas Avatar asked Apr 09 '16 05:04

Lytigas


2 Answers

MongoClient.connect() return a promise if you don't give it a callback, you can declare a global promise :

var connect = MongoClient.connect(url);

socket.on('data', function(data) {
  connect.then(function(db) {

  });
});

socket.on('otherData', function(data) {
  connect.then(function(db) {

  });
});
like image 68
Shanoor Avatar answered Oct 30 '22 08:10

Shanoor


You should be able to load the connection into a var and just use that instead of re-establishing the connection for every query.

I use a similar approach myself, locating the connection code into a its own module, something like so:

NOTE: This code is off-the-cuff, untested, and I'm a little drunk.

connect.js

var MongoClient = require('mongodb').MongoClient;

module.exports = function(params) {

  var ip = params.ip || process.env.IP;
  var port = params.port || 27017;
  var collection = params.collection;

  var db = MongoClient.connect('mongodb://' + ip + ':' + port + '/' + collection);

  return db;

}



Then in any given other module in your app, you would require connection.js and pass the params for any given connection, like so:

onFeedback.js

var feedbackDB = require('./connection.js')({
  collection : 'feedback'
});

socket.on('data', function (data) {
  feedbackDB(function(db){
    db.doStuff();
  };
});
like image 35
AJB Avatar answered Oct 30 '22 08:10

AJB