Connect to MongoDB
suggest changeConnect 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:
err:Errorif the attempt failed, otherwisenullclient: theMongoClient(driver 3.0 and later)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents