Another option for connecting to MongoDB using MongoClient
is to use a connection string. With this option, you use a simple connection string to create, open, and authenticate a connection to the database. The Server
and MongoClient
options used to connect to the database are created in the background. This method has the advantage of being very simple to implement.
To connect to MongoDB via a connection string, you need to call the connect()
method on the MongoClient
class; no instance is required. The connect()
method uses the following syntax:
MongoClient.connect(connString, options, callback)
The connString
string has the following syntax (described in Table 13.4):
mongodb://username:password@host:port/database?options
The options
parameter is an object that can contain db
, server
, rplSet
, and mongos
properties. The db
property is an object that can contain the properties described in Table 13.3. The server
property is an object that can contain the properties described in Table 13.2. The replSet
property is an object that can contain options for handling connections to replica sets. The mongos
property is also an object that can contain options for connecting to a mongos
proxy.
The callback function accepts an error as the first parameter and a Db
object instance as the second parameter. If an error occurs, the Db
object instance is null
; otherwise, you can use it to access the database because the connection has already been created and authenticated.
While in the callback function, you can access the MongoDB database by using the Db
object passed in as the second parameter. When you are finished with the connection, you call close()
on the Db
object to close the connection.
Listing 13.2 is an example of using the connection string method. Line 2 specifies the connection string, and lines 3–10 specify the object that contains the db
, server
, replSet
, and mongos
properties. Lines 12–23 define the callback function. Notice that the callback function is passed a Db
object that is already authenticated, so no authentication is necessary. Figure 13.2 shows the output from Listing 13.2.
01 var MongoClient = require('mongodb').MongoClient;
02 MongoClient.connect("mongodb://dbadmin:test@localhost:27017", {
03 db: { w: 1, native_parser: false },
04 server: {
05 poolSize: 5,
06 socketOptions: { connectTimeoutMS: 500 },
07 auto_reconnect: true
08 },
09 replSet: {},
10 mongos: {}
11 }, function(err, db) {
12 if(err){
13 console.log("Connection Failed Via Connection String.");
14 } else {
15 console.log("Connected Via Connection String . . .");
16 db.logout(function(err, result) {
17 if(!err){
18 console.log("Logged out Via Connection String . . .");
19 }
20 db.close();
21 console.log("Connection closed . . .");
22 });
23 }
24 });