faber-finances/server/utils/db.js
Jennie Robinson Faber 1f18ad001d Update MongoDB connection logging in db.js
- Enhanced connection log to specify 'MongoDB Atlas - Database: faber-finances'
- Added comment clarifying that the database is created automatically upon the first document insertion
2025-08-23 12:22:17 +01:00

42 lines
No EOL
988 B
JavaScript

import { MongoClient } from 'mongodb'
let client = null
let db = null
export async function connectToDatabase() {
if (db) {
return db
}
const uri = process.env.MONGO_URI
if (!uri) {
throw new Error('MONGO_URI environment variable is not set')
}
try {
client = new MongoClient(uri)
await client.connect()
// MongoDB will create the database automatically when first document is inserted
db = client.db('faber-finances')
console.log('Connected to MongoDB Atlas - Database: faber-finances')
return db
} catch (error) {
console.error('Failed to connect to MongoDB:', error)
throw error
}
}
export async function getCollection(name) {
const database = await connectToDatabase()
return database.collection(name)
}
// Close connection (useful for cleanup)
export async function closeDatabaseConnection() {
if (client) {
await client.close()
client = null
db = null
console.log('Disconnected from MongoDB')
}
}