-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.js
More file actions
54 lines (43 loc) · 1.22 KB
/
Copy pathdb.js
File metadata and controls
54 lines (43 loc) · 1.22 KB
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
const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URI;
if (!uri) {
console.warn('MONGODB_URI not set. Set it in your environment.');
}
let client;
let db;
async function connectToDatabase() {
try {
if (db) return db;
if (!uri) {
throw new Error('MONGODB_URI environment variable is not set');
}
// Parse the connection string to extract database name
let dbName = 'smartbite'; // Default database name
const uriParts = uri.split('/');
if (uriParts.length > 3) {
const dbPart = uriParts[3];
if (dbPart && dbPart.includes('?')) {
dbName = dbPart.split('?')[0];
} else if (dbPart) {
dbName = dbPart;
}
}
// Connect with proper options
client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await client.connect();
console.log('Successfully connected to MongoDB');
db = client.db(dbName);
return db;
} catch (error) {
console.error('MongoDB connection error:', error.message);
throw error;
}
}
function getDb() {
if (!db) throw new Error('Database not initialized');
return db;
}
module.exports = { connectToDatabase, getDb };