Connect to MongoDB

suggest change

Connect to MongoDB, print Connected!, and close the connection. Since driver 3.0, the callback's second argument is a MongoClient, not a Db. Select the database with client.db().

const MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017';

MongoClient.connect(url, function(err, client) {
    if (err) throw err;
    console.log("Connected!");
    var db = client.db('test');
    client.close(); // Don't forget to close the connection when you are done
});

MongoClient method connect()

MongoClient.connect(url, options, callback)

Argument Type Description
url string Server host, port, and optional database name
options object (optional) Extra settings (default: null)
callback Function Called when the connection attempt finishes

The callback is error-first:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents