-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0_connection.js
More file actions
52 lines (45 loc) · 1.33 KB
/
0_connection.js
File metadata and controls
52 lines (45 loc) · 1.33 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
// Importing required modules
const { MongoClient } = require('mongodb');
require('dotenv').config();
// Connection URI and database name from environment variables
const uri = process.env.MONGODB_URI;
const dbName = process.env.DATABASE_NAME;
// Create a MongoDB client
const client = new MongoClient(uri);
// Function to connect to MongoDB
async function connect() {
try {
// Connect to MongoDB
await client.connect();
console.log('Successfully connected to MongoDB.');
return client.db(dbName);
} catch (error) {
console.error('Error connecting to MongoDB:', error);
throw error;
}
}
// Function to close the connection
async function closeConnection() {
try {
await client.close();
console.log('MongoDB connection closed.');
} catch (error) {
console.error('Error closing MongoDB connection:', error);
throw error;
}
}
// Example usage
async function testConnection() {
try {
const db = await connect();
console.log('Connected to database:', db.databaseName);
await closeConnection();
} catch (error) {
console.error('Test connection failed:', error);
}
}
// Run the test if this file is run directly
if (require.main === module) {
testConnection();
}
module.exports = { connect, closeConnection };