What's the best way to connect to MongoDB with typescript that reuses the existing connection. I recently migrated my JavaScript codebase to typescript and the MongoDB connection in typescript throws an error
Please I need how to connect with MongoDB driver with typescript in such a way that I can reuse the existing database connection or help me fix my connection problem
Here is the error from the code below (node:3732) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'conn' of undefined
import { MongoClient, Db } from "mongodb";
const { DATABASE_URL, DATABASE_NAME } = process.env;
type MongoConnection = {
client: MongoClient;
db: Db;
};
declare global {
namespace NodeJS {
interface Global {
mongodb: {
conn: MongoConnection | null;
promise: Promise<MongoConnection> | null;
};
}
}
}
let cached = global.mongodb;
async function connectToDatabase() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
cached.promise = MongoClient.connect(DATABASE_URL as string, opts).then(
(client) => {
return {
client,
db: client.db(DATABASE_NAME),
};
}
);
}
cached.conn = await cached.promise;
return cached.conn;
}
export { connectToDatabase };