File size: 2,416 Bytes
e9d5b7d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
// 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<MongoClient>;
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);
}
|