0

I am trying to separate the connection to mongodb using nodejs and the current code looks like this in a file mongodb.js:

const mongoClient = require('mongodb').MongoClient;
const env = process.env.NODE_ENV || 'development';
const mongoDbUrl = require('../config/mongodb.json')[env];
let mongodb;

function connect(cb){
    mongoClient.connect(mongoDbUrl.url, (err, db) => {
        if (err) return "Could not connect to mongodb" ;
        else{
            console.log("Connection to mongodb is successful")
        }
        mongodb = db;
        cb();
    });
}
function get(){
    return mongodb;
}

function close(){
    mongodb.close();
}

module.exports = {
    connect,
    get,
    close,
};

and in other files for ex app.js I use it as:

const mongodb = require('../config/mongodb');
mongodb.connect(() => {
    mongodb.get().collection('tyk_organizations').find({}).toArray()
        .then((users) => {
            console.log('organizations ', users);
        });
});

Error I get:

mongodb.get(...).collection is not a function

Mizlul
  • 1
  • 7
  • 41
  • 100

1 Answers1

1

Try this:

// dbConnection.js
const MongoClient = require('mongodb').MongoClient;
const env = process.env.NODE_ENV || 'development';
const mongoDbUrl = require('../config/mongodb.json')[env];
let client;

module.exports = async () => {
  // this gives you client
  // Mongoclient.connect returns promise if no callback is passed
  try {
    client = await MongoClient.connect(mongoDbUrl.url, { useNewUrlParser: true });
  } catch (e) {
    console.log("Could not connect to mongodb");
  }
}

module.exports.get = () => client;

module.exports.close = () => client.close()

In your server or app

const connect = require('./dbConnection')
// establish connection
connect()

Elsewhere you can use like:

const { get } = require('./dbConnection')
// client is a promise
const client = get();
// then you can use like
client.db(dbName).collection(collName)...
1565986223
  • 6,420
  • 2
  • 20
  • 33
  • 1
    `connect()` as you have defined it is **still a Promise**, and you need to `await` that. You seem to think that just because you used `await MongoClient` inside a `try..catch` that the "promise has gone away". It has not. See also [await vs return vs return await](https://jakearchibald.com/2017/await-vs-return-vs-return-await/) and in particular the usage of the initial `waitAndMaybeReject()` function through the examples. – Neil Lunn Mar 29 '19 at 23:30
  • FYI, the error was somewhere else not with `connect()`. Corrected the mistake! – 1565986223 Mar 30 '19 at 04:34
  • 1
    So `connect()` is a Promise, and you did not `await `it or use a `.then()` before presenting any continuing logic. Hence since you did not do that you do not "appear" to be aware of that mistake. And apparently still do not since that has not been corrected here at all, and would be misleading advice to anyone reading. Please note you were being given a helpful correction to something you did not appear to be aware of and an mistake in the presented code. So you probably should not be so quick to rush to judgement. Also, duplicate question is marked and you suggested that yourself, – Neil Lunn Mar 30 '19 at 04:43
  • 2
    Also, more that a little dangerous to call a localized module by the same name as an import intended from `node_modules`. If nothing else it's easily misinterpreted by the casual reader, – Neil Lunn Mar 30 '19 at 04:45