Proper way to cleanup a mongo db() reference?

Viewed 64

I'm making a multi tenant app using mongo db and would like to know what the proper procedure between switching between databases is. I know I can get a new reference to a database using the db() command:

const client = await MongoClient.connect(url);
client.mainDb = client.db('main');
app.set('mongoClient', client);

On bootup I get and store a reference to my main for all my global app data. Then each request also passes in a tenant id. I'm using Feathersjs which provides me with a hook for every request before and after.

In my before hook, I get a reference to the clients data and store it to be used during that singular request:

app.hooks({
    before: {
        all: [(context) => {
            // Run before all API requests
            const tenant = context.params?.query?.$tenant;
            const tenantDbName = ... // some logic to query the tenant db name

            const client = context.app.get('mongoClient');
            context.params.tenantDb = client.db(tenantDbName);
        }]
    }
}

After the request, I'm unclear on if I should do anything to cleanup the connection. Do I just let the garbage collector clean it up since its request that was made which has ended? Or is there a function in Mongo to clean it up?

app.hooks({
    after: {
        all: [(context) => {
            // Cleanup DB or reset connection?
            context.params.tenantDb = null;
        }]
    }
}

I just need to ensure that the next request doesn't use a previous requests database as this could serve them other users data.

0 Answers
Related