0

First of all it is a similar question like How to properly reuse connection to Mongodb across NodeJs application and modules, but I guess due to the ES6 syntax it's still different.

So I decided to use MongoDriver and created a class for this like in SO answer: dbconnections.js

import { default as mongodb } from 'mongodb';
const MongoClient = mongodb.MongoClient;
const url = "myurl"
let _db;

export const connectToServer = async (callback) => {
    try {
        MongoClient.connect( url,  { useNewUrlParser: true, useUnifiedTopology:true }, ( err, db ) => {
            _db  = db
            return callback( err )
        })
    } catch (e) {
        throw e
    }
}  
      
export const getDB = () => _db

export const disconnectDB = () => _db.close()

The problem with this module is, that due to the ES6 syntax is that I can't make like something this

import {getDB} from '../dbconnections.js'
const driverDB=getDB()

export const someFunction= async (req,res) => {
    console.log(driverDB)

because I always get undefiened so I have to call my getter in every function.

So my question: how to create properly a structure for a MongoDriver handler and pass this to different modules with ES6?

MrNobody
  • 535
  • 8
  • 24

1 Answers1

0

Pass the client object into objects and functions that need it.

https://en.wikipedia.org/wiki/Dependency_injection

D. SM
  • 13,584
  • 3
  • 12
  • 21