0

I am creating the nodejs application which uses the mongodb.

I am connecting to mongodb only once. I want to use db in all other api's so as to achieve the connection pooling.

I have following code for mongodb connectivity:

var mongodb = require('mongodb');

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

var mongoUrl = "mongodb://localhost:27017/testDB";
/**
 * Connects to the MongoDB Database with the provided URL
 */


exports.connect = function(callback){
    if(!db){
        MongoClient.connect(mongoUrl, function(err, _db){
            if (err) { throw new Error('Could not connect: '+err); }
            db = _db;
            console.log(db);
            connected = true;
            console.log(connected +" is connected?");
            callback(db);
        });     
    }else{
        console.log("Not connected tis time as I am already connected");
        callback(db);
    }

};


exports.db = db;

I am calling connect only once when server starts from app.js. Whenever other api such as signin, register get called, they should simply use db that is exported.

So my api calls will something like(please ignore the syntax error in api call :D):

var mongo  = require('./mongo');

collection = mongo.db.collection("testCollection");
// Here mongo.db id undefined
collection.findOne({"name":"John"}, function(err, result){
   // Do your stuff with result here
});

From other stackoverflow posts, I tried something like in mongo.js as

module.export{
db: db,
connect : function(callback){
  //function code goes here
}
}

But still I am getting the undefined for mongo.db How would I access mongo.db in my other files? Thanks

3 Answers 3

1

The reason this happens is, because connect overwrites db in the module. The exports.db=db; is not executed after calling your connect function, but on execution of the module import.

So, when you call connect, db is set to another variable, but that is not exposed outside.

Didn't do much JS lately, but this should do it:

module.exports = new mongobj();

function mongobj() {
   this.db = null;
   this.connect = function(callback) { /* your connect code set mongobj.db */
      this.db = /* new value */ ;
   }
}

When you import the module, you get the object. Accessing the objects db property will always expose the latest db value set by the connect function of the module.

var mongo = require('yourmodule');

// mongo.db is null
mongo.connect(some callback);
// mongo.db is set
Sign up to request clarification or add additional context in comments.

1 Comment

then How would I get updated value? Is there is way or it is not possible
1

This connection add in main script file...

var mongodb = require('mongodb');
var mongodb = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var mongoUrl = "mongodb://localhost:27017/testDB";


ObjectId = module.exports = require("mongojs").ObjectId;
MongoClient.connect(mongoUrl, function(err, database){
    if(err){
        console.log("mongodb error >>"+err);    
    } else {
        db = module.exports = database;
    }});


db.collection('game_users').findOne({_id:ObjectId("123456789")},function(err, data) {});

Comments

0

define an object:

var db = {__db: undefined}

and then:

exports.db = db
const db = require('./mongo').db.__db

Comments

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.