// IMPORTANT: Storing connection strings directly in code is insecure for production. // This connection string should be moved to an environment variable (e.g., in a .env file) // and accessed via `process.env.MONGODB_URI`. // Example for .env: // MONGODB_URI="mongodb+srv://davidcyril209:YOUR_PASSWORD_HERE@david.sfonwmo.mongodb.net/?retryWrites=true&w=majority&appName=David" // Make sure to replace YOUR_PASSWORD_HERE with your actual password. import { MongoClient, ServerApiVersion } from 'mongodb'; const MONGODB_URI = "mongodb+srv://davidcyril209:85200555dcx@david.sfonwmo.mongodb.net/?retryWrites=true&w=majority&appName=David"; if (!MONGODB_URI) { throw new Error( 'Please define the MONGODB_URI environment variable inside .env or provide it directly' ); } // Create a MongoClient with a MongoClientOptions object to set the Stable API version const client = new MongoClient(MONGODB_URI, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } }); let clientPromise: Promise; if (process.env.NODE_ENV === 'development') { // In development mode, use a global variable so that the value // is preserved across module reloads caused by HMR (Hot Module Replacement). // @ts-ignore if (!global._mongoClientPromise) { // @ts-ignore global._mongoClientPromise = client.connect(); } // @ts-ignore clientPromise = global._mongoClientPromise; } else { // In production mode, it's best to not use a global variable. clientPromise = client.connect(); } // Export a module-scoped MongoClient promise. By doing this in a // separate module, the client can be shared across functions. export default clientPromise; export async function getDb() { const client = await clientPromise; // The database name can be part of the connection string or specified here. // If your connection string includes a database name (e.g., /myDatabaseName?), // MongoDB driver might use that. Otherwise, you need to specify it. const uriParts = MONGODB_URI.split('/'); const dbNameFromUri = uriParts[uriParts.length-1]?.split('?')[0]; // Use the database name from the URI if it's present and not a generic part of the query string. // Otherwise, default to 'anitaDeployDB'. const dbName = (dbNameFromUri && !dbNameFromUri.includes("retryWrites")) ? dbNameFromUri : 'anitaDeployDB'; return client.db(dbName); }