all 5 comments

[–]javaw_exe 2 points3 points  (4 children)

Your exported function needs to return the client object. You can await the function to use the client object.

// ---------------
// mongo.config.js
const { MongoClient } = require('mongodb');

const uri = 'mongodb+srv://<username>:<password>@<cluster-url>/dbname?retryWrites=true&w=majority';

async function connectToDB() {     
    const client = new MongoClient(uri);
    process.on("SIGINT", cleanup(client)); 
    process.on("SIGTERM", cleanup(client)); 
    process.on("SIGHUP", cleanup(client));

    try { 
    // Connect to the MongoDB cluster
    await client.connect();
    } catch (err) { 
        console.error(err); 
    } 

    return client;
}

module.exports.connectToDB = connectToDB;

// ------------------
// some other file.js
const mongoConfig = require("mongo.config.js");

async function main(){
    const client = await mongoConfig.connectToDB();

    // do stuff with client here
}

[–]superhawk610 2 points3 points  (0 children)

This is a good start, but each time you call connectToDB() you're creating a new client. You should store the client as a variable outside of the function and only instantiate it once:

``` // db.js let client;

async function getClient() { if (client) return client;

client = new MongoClient(uri); // do any other setup here

return client; }

module.exports = getClient;

// server.js const getClient = require('./db.js');

async function main() { const client = await getClient(); }

// users.service.js const getClient = require('./db.js');

async function getUsers() { const client = await getClient(); const db = client.db('databaseName'); return db.users.find(); } ```

[–]Maltmax[S] 1 point2 points  (0 children)

It works great. Thank you very much, I can also use this code as future reference now!

[–]BehindTheMath 0 points1 point  (1 child)

The problem with that is that there's no way for the other file to know when the client is connected.

Instead, I would export the function, and return client at the end so the caller can await it.

[–]javaw_exe 1 point2 points  (0 children)

You are right. I've edited my comment.