I'm developing a node.js app and I'm passing mongoDB into functions, so it is easier to unit test, as I can mock my production mongoDB with a test mongoDB database. However, I am not sure I'm doing it correctly as I think I might be creating multiple client instances;
//db.js
import mongodb from 'mongodb';
export default async function makeDb() {
const { MongoClient } = mongodb;
const url = process.env.DB_URL;
const client = new MongoClient(url,
{
useNewUrlParser: true,
useUnifiedTopology: true,
});
await client.connect();
const db = await client.db('myDB');
return db;
}
and then I import the makeDB function and pass it into multiple dbHandlers;
//authHandler.js
import makeDB from './db'
export default function dbMethods({ makeDB }) {
const signup = async (username, password) => {
const db = await makeDB();
const result = await db
.collection('users')
.insertOne({ username, password });
return result;
};
// other methods that also use const db = await makeDB();
return Object.freeze({
signup,
// other methods
});
}
Apart from the authHandler, I have also other handlers in my application that use the same technique.
Am I creating dozens of mongoDB client instances every time I do const db = makeDB()? If so, is there a better way of doing it