What's the proper way to re-use the MongoDB NodeJS Driver?

Here’s a simple working example:

import { MongoClient } from 'mongodb'

const uri = 'mongodb://localhost:27017'
const client = new MongoClient(uri)

async function data(collection: string, database: string = 'default') {
    await client.connect()
    return client.db(database).collection(collection)
}

const resolvers = {
    Query: {
        example: async () => {
            const cursor = (await data('example'))
                .find()
                .toArray()
                .finally(() => client.close())
            return cursor
        }
    }
}

Is this the proper way to connect to MongoDB? Is this the correct way to close a connection, and is it required? Is this the most optimal way to use MongoDB; if not, how can this be done suitably?

The “Resolver” is a GraphQL resolver.

No it is not. You do not want to connect() at every query. You want to reuse the same connected client between queries.

The problem with this code is you rely on the code making the query to close(). If one forget to close() you might end up with multiple open connections.

Take a look at the course M220JS from MongoDB university. It does not use GraphQL but the principles of DAO module would be the same.

1 Like

Thanks a lot for the feedback :clap: