3

I have searched a lot but still wasn't able to find a specific ans. I am trying to do following:

In mongo.js

var client = require('mongodb').MongoClient,
mongodb=null;

module.exports =  {
connect: function(dburl, callback) {
    client.connect(dburl,
        function(err, db){
            mongodb = db;
            if(callback) { callback(); }
        });
},
db: function() {
    return mongodb;
},
close: function() {
    mongodb.close();
 }
};

In server.js

mongodb = require('./mongo');
mongodb.connect('mongodb://localhost:27017/mydb', function() {
 console.log('Connected to MongoDB.');
});

In randomfile.js

 mongodb = require('./mongo');
 mongodb.db()
.collection('mycollection')
.find({someField: 'myquery'}, {}, options)
.toArray(function(err, coll) {
    if (err) { throw err; }
    console.log(coll);
});

When I run server.js a connection is formed but when I run randomfile.js I am not able to get the connection. I encounter following error.

TypeError: Cannot read property 'collection' of undefined

Am I doing something wrong?

2
  • Why do you not invoke mongo.connect and pass it the address in randomfile.js? I don't see how you expect to get a reference to your database in randomfile.js. Commented May 25, 2015 at 17:58
  • I am afraid thats the whole of it. Commented May 25, 2015 at 17:58

1 Answer 1

2

When you do anything after the callback gets over, the connection does not persist. To preserve the connection, use connection pooling.

var db; //global database instance
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
  if(err) throw err;

  db = database;  //pool the connection
  coll = db.collection('test');

  app.listen(3000);
  console.log('Listening on port 3000');
});
//No need for further calls to connect(), reuse db
//object. Export to other files if necessary.

More info.

For a larger application, a better solution would be to modularize the connection and use it again across all the files of the app.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks bluefog. Ya but if for each interaction I need to open a connection to db then, it will introduce a lot of latancy. My object was to create a single connection per db and share across all apis/interaction. Is there any way to achieve this?
@bhaumik Creating a connection to the database is usually not a bottleneck. How do you know that repeated connection will create latency issues? Have you faced any issues?
No i haven't till now but I can see that it takes some milli seconds to form a connection and since I am working on a scalable application, this can affect when there are many requests forming connections to same db. Correct me if I am wrong.
thanks for the link. I had already seen it. Since, my code is purely backend (no use of express js), this type of pooling won't help. I guess I need to use some other language, for this purpose.
@bhaumik That does not make much sense to me. Connection pooling can be done on any call of connect. It has nothing to do with express at all.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.