Synchronized Connection on MongoDB

I’m using a synchronized database connection for my project and I’m wondering does it cause trouble? Let me explain, how i use this. When the application starts life it connects to the database and it is using one connection until application dies. I prefered this because I need to export database to other documents for db queries. This is my code:

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';

function connectToDB() {
    const client = new MongoClient(uri);

    try {

        setTimeout(() => {
            console.log(`\x1b[32m[DONE]\x1b[0m db connection established.`)
        }, 200);
        return client.db('serverDatabase')

    } catch (error) {
        console.error('error:', error);
        throw error;

module.exports = connectToDB();

Im not sure what you mean by “synchronized” and “connection” here.

But i believe it’s a general practice to maintain only one such instance (db/client, or similar) and share it with multiple threads.

That was my main purpose in doing this. This isn’t async function so I’m wondering would it be a problem because the client connection is not async

No, people always do this. If you see this as a problem, then something wrong with your code/service/deployment/…etc.

that being said, some drivers may have async support. (e.g. i recall java does).

1 Like