GovindarajanD
GovindarajanD

Reputation: 3

MongoDB-Express: Cannot get the client/db out of connect function

I am separating the connect function of MongoDB to a separate module, so that the mongoDB connection is reusable. The issue is, I could not get the client/DB variable outside the connect function. It shows undefined.

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

var _client;
var mongoURL = "mongodb://localhost:27017/";

module.exports = {
    connectToMongoServer: (callback) => {
        MongoClient.connect(mongoURL,{ useNewUrlParser: true },function(err,client){
            _client = client;
            return callback(err);
        });
    },
    getClient: () => {
        return _client;
    }
};

Within the connect function, the _client details contains the information, but if I return it using getClient, it shows undefined.

MongoDB - v3.6.5

Node - v9.9.0

Upvotes: 0

Views: 440

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23515

I've made up a snippet which should work the same ad your code, and it works. So I think the problem is how you are calling your function getClient(); are you sure you are calling it after it get connected?

var _client;

function someAsyncFunc(callback) {
 setTimeout(() => callback(false, 'client'), 500);
}

const file = {
  connectToMongoServer: (callback) => {
   someAsyncFunc(function(err, client) {
      _client = client;
      
      return callback(err);
    });
  },
  
  getClient: () => {
    return _client;
  }
};

console.log('display one :', file.getClient());

file.connectToMongoServer((err) => {
  console.log('display error :', err);
  
  console.log('display two :', file.getClient());
});

Upvotes: 1

Related Questions