Using a MongoClient
object to connect to MongoDB involves creating an instance of the client, opening a connection to the database, authenticating to the database if necessary, and then handling logout and closure as needed. This method has the advantage of allowing you to manipulate each step of the connection and authentication.
To connect to MongoDB via a MongoClient
object, you need to first create an instance of the MongoClient
object. The constructor for the MongoClient
class takes a Server
object as the first parameter and an object specifying the database connection options as the second parameter, as shown below:
MongoClient(Server, options)
Table 13.3 lists the most important database connection options that can be set and applied to the MongoClient
connections:
The following example shows how to create a MongoClient
instance. Notice that a Server
object is created using options from Table 13.2:
var client = new MongoClient(new Server('localhost', 27017, { poolSize: 5}),
{ retryMiliSeconds: 500 }));
Once you have created MongoClient
, you need to open a connection to the MongoDB server database by using the open(callback)
method. The callback method is called with an error as the first parameter if the connection fails and a MongoClient
object as the second parameter if the connection is successful. For example:
client.open(function(err, client){ . . . });
To connect to a specific database, you need to create an instance of the database by using the db(databasename)
method on the client
object. You use the database connection options to create a Db
object instance that can be used to access collections in a specific database. If you have authentication turned on, you also need to authenticate to the database by using the db.authenticate(username, password, callback)
method before trying to access it. For example:
var db = client.db("testDB");
db.authenticate("dbadmin", "test", function(err, results) { . . .});
To log out of the database, use the logout()
method on the Db
object. This closes the connection to the database, and you can no longer use the Db
object. For example:
db.logout()
To close the connection to MongoDB, you call close()
on the client connection as shown below:
client.close()
Listing 13.1 puts together all this connection stuff in a simple example. Notice that the code creates a client connection object on line 3 by generating a Server
object and passing in some additional options. Also notice that the client connection is not established until line 11, when open
is called. On line 15 a connection to the testDB
database is made, and it’s authenticated on line 18. Then inside the authenticate()
callback function, the db()
connection is logged out, and the client connection is closed. Figure 13.1 shows the output from Listing 13.1.
01 var MongoClient = require('mongodb').MongoClient,
02 Server = require('mongodb').Server;
03 var client = new MongoClient(new Server('localhost', 27017, {
04 socketOptions: { connectTimeoutMS: 500 },
05 poolSize: 5,
06 auto_reconnect: true
07 }, {
08 numberOfRetries: 3,
09 retryMilliSeconds: 500
10 }));
11 client.open(function(err, client) {
12 if(err){
13 console.log("Connection Failed Via Client Object.");
14 } else {
15 var db = client.db("testDB");
16 if (db){
17 console.log("Connected Via Client Object . . .");
18 db.authenticate("dbadmin", "test", function(err, results){
19 if (err){
20 console.log("Authentication failed . . .");
21 client.close();
22 console.log("Connection closed . . .");
23 }else {
24 console.log("Authenticated Via Client Object . . .");
25 db.logout(function(err, result) {
26 if(!err){
27 console.log("Logged out Via Client Object . . .");
28 }
29 client.close();
30 console.log("Connection closed . . .");
31 });
32 }
33 });
34 }
35 }
36 });