xxxxxxxxxx
const { MongoClient } = require('mongodb');
async function connectToDatabase() {
const uri = 'mongodb://localhost:27017'; // MongoDB connection string for localhost
const client = new MongoClient(uri);
try {
// Connect to the MongoDB server
await client.connect();
console.log('Connected to the database.');
// Do your database operations here...
} catch (error) {
console.error('Unable to connect to the database:', error);
} finally {
// Close the connection once you're done
await client.close();
console.log('Connection closed.');
}
}
// Call the function to establish the connection
connectToDatabase();
xxxxxxxxxx
// Import the required MongoDB driver
const MongoClient = require('mongodb').MongoClient;
// Connection URL for the local MongoDB instance
const url = 'mongodb://localhost:27017';
// Creating a new MongoClient instance
const client = new MongoClient(url, { useNewUrlParser: true });
// Connect to the MongoDB server
client.connect(function(err) {
if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}
console.log('Connected successfully to MongoDB');
// Perform further operations on the database
// Close the connection when done
client.close();
});