Access MongoDB Outside of the Connection Callback

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

In any case, basically my node server receives socket.io event data. I want this data to go into MongoDB. The problem is that all the code examples I've seen for mongo only manage db inside the callback MongoClient.connectusing the object db.

Since I get a lot of this data, I do not want to initialize again and again.

I really need:

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

And then:

socket.on('data', function (data) {
    db.doStuff();
});
+4
source share
2 answers

MongoClient.connect() , , :

var connect = MongoClient.connect(url);

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

  });
});

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

  });
});
+4

var .

, , :

: , , .

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;

}



connection.js params , :

onFeedback.js

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

socket.on('data', function (data) {
  feedbackDB(function(db){
    db.doStuff();
  };
});
+1

All Articles