xxxxxxxxxx
async function main(){
/**
* Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
// Make the appropriate DB calls
await listDatabases(client);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
xxxxxxxxxx
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://127.0.0.1:27017'; // Use IPv4 address
const dbName = 'your-database-name';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}
console.log('Connected to MongoDB successfully');
const db = client.db(dbName);
// Your MongoDB operations here
client.close(); // Close the MongoDB connection when done
});
xxxxxxxxxx
// Connect to MongoDB
const mongoConnection = new DatabaseConnection();
await mongoConnection.connect();