-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.js
More file actions
59 lines (50 loc) · 1.27 KB
/
Copy pathdatabase.js
File metadata and controls
59 lines (50 loc) · 1.27 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
54
55
56
57
58
59
const { MongoClient } = require('mongodb')
require('dotenv').config()
class Database {
constructor () {
this.client = null
this.db = null
}
async connect () {
try {
const uri = process.env.MONGODB_URI
console.log('Connecting to MongoDB...')
this.client = new MongoClient(uri)
await this.client.connect()
this.db = this.client.db(process.env.MONGODB_DATABASE)
console.log('Successfully connected to MongoDB')
return this.db
} catch (error) {
console.error('MongoDB connection error:', error)
throw error
}
}
async disconnect () {
try {
if (this.client) {
await this.client.close()
console.log('Disconnected from MongoDB')
}
} catch (error) {
console.error('Error disconnecting from MongoDB:', error)
}
}
getDb () {
if (!this.db) {
throw new Error('Database not connected. Call connect() first.')
}
return this.db
}
async testConnection () {
try {
const db = this.getDb()
await db.admin().ping()
console.log('Database connection test successful')
return true
} catch (error) {
console.error('Database connection test failed:', error)
return false
}
}
}
module.exports = new Database()