Node & MongoDB - Connecting Database



Node mongodb provides mongoClient object which is used to connect a database connection using connect() method. This function takes multiple parameters and provides db object to do database operations.

Syntax

// MongoDBClient
const client = new MongoClient(url, { useUnifiedTopology: true });
// make a connection to the database
client.connect();

You can disconnect from the MongoDB database anytime using another connection object function close().

Syntax

client.close()

Example

Try the following example to connect to a MongoDB server −

Copy and paste the following example as mongodb_example.js −

const MongoClient = require('mongodb').MongoClient;
// Prepare URL
const url = "mongodb://localhost:27017/";
// make a connection to the database
MongoClient.connect(url, function(error, client) {
   if (error) throw error;
   console.log("Connected!");
   // close the connection
   client.close();
});

Output

Execute the mysql_example.js script using node and verify the output.

node mongodb_example.js
Connected!
Advertisements