Connect to MongoDB
suggest changeConnect to MongoDB, print ‘Connected!’ and close the connection.
const MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) { // MongoClient method 'connect'
if (err) throw new Error(err);
console.log("Connected!");
db.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 | A string specifying the server ip/hostname, port and databaseoptions
| object | (optional) Optional settings (default: null)callback
| Function | Function to be called when the connection attempt is done
The callback
function takes two arguments
err
: Error - If an error occurs theerr
argument will be defineddb
: object - The MongoDB instance
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents