-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
39 lines (30 loc) · 1.1 KB
/
Copy pathdatabase.js
File metadata and controls
39 lines (30 loc) · 1.1 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
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017'; // Replace with your MongoDB server URL
// Database Name
const dbName = 'mydatabase'; // Replace with your database name
// Create a new MongoClient
const client = new MongoClient(url);
// Use async/await to connect to the database
async function connectToDatabase() {
try {
// Connect to the MongoDB server
await client.connect();
// Select the database
const db = client.db(dbName);
console.log('Connected to the database');
// You can now perform operations on the database
// For example, insert a document into a collection
const collection = db.collection('mycollection');
const document = { name: 'John', age: 30 };
const result = await collection.insertOne(document);
console.log(`Inserted document with _id: ${result.insertedId}`);
} catch (err) {
console.error('Error connecting to the database:', err);
} finally {
// Close the connection when you're done
await client.close();
}
}
// Call the connectToDatabase function
connectToDatabase();