-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
39 lines (31 loc) · 1.11 KB
/
database.js
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
const { MongoClient } = require("mongodb");
// Replace the connection string with your MongoDB Atlas connection string
const uri =
"mongodb+srv://dhruv75277:[email protected]/?retryWrites=true&w=majority";
async function connectToDatabase() {
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
try {
await client.connect();
console.log("Connected to MongoDB Atlas");
// Now you can perform database operations using the "client" object
// Example: List all databases
// await listDatabases(client);
} finally {
// Close the connection when the application is done
// await client.close();
// console.log("Connection closed");
}
}
// Function to list all databases
async function listDatabases(client) {
const databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach((db) => {
console.log(`- ${db.name}`);
});
}
// Call the function to connect to the database
module.exports = connectToDatabase();