Init commit!
This commit is contained in:
commit
086d682592
34 changed files with 19249 additions and 0 deletions
41
server/utils/db.js
Normal file
41
server/utils/db.js
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
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()
|
||||
db = client.db('faber-finances')
|
||||
console.log('Connected to MongoDB')
|
||||
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')
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue