user269867
user269867

Reputation: 3952

mongodb connection is not getting resolved in nodejs

I am trying to code refactor to ensure that mongodb instance is instantiated only once.

const dbs = async () => await new Promise((resolve, reject) => {
    const mongoClient = new mongodb.MongoClient(dbUrl, {
        useUnifiedTopology: true,
    });

    mongoClient.connect((err, client) => {
        if (err) {
          console.log(`err while connecting`);
          reject(err);
          return;
        }
        console.log('Successfully connected to db');
        return resolve(client);
    });
});
module.exports = dbs;

In my test.js I am doing as follow

const dbscl = require('./dbcon'); 
const setdb = dbscl.db(dbName);

I am getting error : dbscl.db is not a function . Any clue why dbs is not resolve as valid database connection?

Upvotes: 0

Views: 67

Answers (1)

Umer Abbas
Umer Abbas

Reputation: 1876

You are exporting function as dbs but you are calling it as db in dbscl.db(dbName) and the other thing you are not exporting it correctly. Learn more about how to export modules in nodejs

You can export function like

module.exports = { dbs }

//Or
module.exports = { 
  dbs: dbs
}

//Or
module.exports.dbs = dbs

Now you can call your function like

const dbscl = require('./dbcon');
const setdb = dbscl.dbs('dbName');

Upvotes: 1

Related Questions