Using MongoDB with Node.js: Using a Connection

In the following subsections we shall create a connection with MongoDB server and create a database instance.

1. Creating a MongoDB Connection

In this section we shall connect to MongoDB server using the Node.js driver for MongoDB. We shall use the MongoClient class for connecting to MongoDB server. The MongoClient constructor does not take any args and has the following syntax.

MongoClient()

The MongoClient class supports the methods (static and instance) discussed in Table 5-2.

The components of the connection URI are discussed in Table 5-3.

The following are some of the simpler URI examples to connect to MongoDB server and are suitable for most purposes.

mongodb://

mongodb://localhost

mongodb://user1:password1@localhost

mongodb://user1:password1@localhost/test

mongodb://localhost:27017.,localhost:27018,localhost:27019

mongodb://example1.com,example2.com

Some of the main connection string options are discussed in Table 5-4.

The write concern options describe the guarantees of a write operation such as whether the write operation has been committed. The different levels of the write concern are discussed in Table 5-5.

The options parameter in the connect(url, options, callback) method supports the options discussed in Table 5-6.

The callback parameter of the connect() method is of type connectCallback(error, db) and defines the callback format for results. The error arg is of type MongoError and represents an error instance. The db arg is of type Db and represents the connected database.

  1. Create a connection.js script in the C:\Program Files\nodejs\scripts directory. The only method available to connect to MongoDB with Node is the connect() method, which has a static version and an instance version, and makes use of a connection URI. As listed before the syntax of the connection URI is as follows.

mongodb://[username:password@]host1[:port1][,host2[:port2],…

[,hostN[:portN]]][/[database][?options]]

The required segment of the connection URL is mongodb://host1. The portl defaults to :27017.

The host2[:port2],…[,hostN[:portN]] segment is not required if not using a replica set, which we won’t be in this chapter. We won’t also be using connection credentials username:password.

  1. Import the MongoClient class from the mongodb module as follows using require statements.

MongoClient = require(‘mongodb’).MongoClient;

  1. Create a MongoClient instance.

var mongoclient = new MongoClient();

Next, we shall connect using the connect(url, options, callback) method in which the first parameter is the connection URI, the second the options, and the third the callback function. The callback function is called after the connect() method completes. The first arg of the callback function is an MongoError object if an error occurs or null and the second arg is an initialized Db object.

  1. Connect with MongoDB server using the connect() method and in the connection URI specify the database as test. In the method block for the callback function log an error message to the console if an error occurs or log a message to indicate that the connection got established if an error does not occur.

mongoclient.connect(“mongodb://localhost:27017/test”, function (error, db) {

if (error)

console.log(error);

else

console.log(‘Connected with MongoDB’);

});

The static method MongoClient.connect() may also be used to connect to MongoDB server and supports the same parameters as the instance method connect().

The connection.js script is listed:

MongoClient = require(‘mongodb’).MongoClient;

var mongoclient = new MongoClient();

mongoclient.connect(“mongodb://localhost:27017/test”, function (error, db) {

if (error)

console.log(error);

else

console.log(‘Connected with MongoDB’);

});

  1. Open a new terminal/console and navigate to C:\Program Files\nodejs.
    Run the connection.js script in Node.js with the following command.

>node connection.js

As the output in Figure 5-11 indicates, the method connect() establishes a connection with MongoDB.

2. Using the Database

In this section we shall discuss the Db class and create a MongoDB database instance. The Db class constructor has the following syntax.

Db(databaseName, topology, options)

The constructor parameters are discussed in Table 5-7.

The options supported by Db class constructor are discussed in Table 5-8.

The Db class provides the properties discussed in Table 5-9.

Some of the methods supported by the Db class are discussed in Table 5-10.

  1. Create a JavaScript script db.js in the C:\Program Files\nodejs\scripts directory.
  2. In the script we shall get a database instance and get a list of database collections from the database. First, import the MongoClient and Db classes from the mongodb module using require.

MongoClient = require(‘mongodb’).MongoClient;

Db = require(‘mongodb’).Db;

A Db instance is not required to be created directly using the class constructor but may be created implicitly by the MongoClient connect() method as the second parameter to callback function.

  1. Create a MongoClient instance.

var mongoclient = new MongoClient();

  1. Connect with the database using the connect(url, options, callback) method. Specify the URI as mongodb://localhost:27017/local, which includes the database instance as local. In the method block for the callback function, log an error message to the console if an error occurs; otherwise log the message ‘Connected with MongoDB’.

mongoclient.connect(“mongodb://localhost:27017/local”, function(error, db) {

if (error

console.log(error);

else

console.log(‘Connected with MongoDB’);

});

We shall use the listCollections(filter, options) method to list the collections in the local database. The listCollections(filter, options) may optionally specify a filter, for example, the filter {name: “collection1”} gets only the collection1 collection. The only option supported by listCollections() is batchSize. The listCollections() method returns a CommandCursor, which provides several methods including the toArray(callback) method to return an array of documents, the each(callback) method to iterate over the documents in the collection, and the next() method to get the next document.

  1. Within the method block for the callback function of the connect() method, output the list of collections.

db.listCollections().toArray(function(err, items) {

console.log(items);

db.close();

});

The db.js script is listed below.

MongoClient = require(‘mongodb’).MongoClient;

Db = require(‘mongodb’).Db;

var mongoclient = new MongoClient();

mongoclient.connect(“mongodb://localhost:27017/local”, function(error, db) {

if (error

console.log(error;

else

console.log(‘Connected with MongoDB’);

db.listCollections().toArray(function(err, items) {

console.log(items); db.close();

});

});

  1. Open a new terminal/window and navigate to C:\Program Files\nodejs. Run the db.js script with the following command.

>node db.js

The different collections in the local database and their options get listed as shown in Figure 5-12.

The Db() class constructor creates a new database instance but does not create a new database as we shall demonstrate next.

  1. Using the same script db.js, comment out the section of code for the mongoclient.connect() method invocation. Add a require statement for the Server class.

Server = require(‘mongodb’).Server;

  1. Create a new instance of Db using the class constructor new Db(databaseName, topology, options) with database name as ‘mongo’ and topology created using the Server class with host as localhost and port as 27017.

var db = new Db(‘mongo’, new Server(‘localhost’, 27017));

  1. Open a connection with the database using the open(callback) method. The callback type for the open() method is openCallback(error, db). Log error if generated. Output a list of collections using the Db instance returned if open is successful.

db.open(function(error, db) {

if (error)

console.log(error);

db.listCollections().toArray(function(error, items) {

console.log(items);

db.close();

});

});

The db.js used for the preceding example is listed below.

Db = require(‘mongodb’).Db;

Server = require(‘mongodb’).Server;

var db = new Db(‘local’, new Server(‘localhost’, 27017)); db.open(function(error, db) {

if (error)

console.log(error);

db.listCollections().toArray(function(error, items) {

console.log(items);

db.close();

});

});

  1. Run the db.js script to list the collections in the mongodb database as shown in Figure 5-13.

In the preceding example we used the Server topology. The topology could also be Mongos or ReplSet.

For example, to use the Mongos topology, follow these steps:

  1. Add a require statement for Mongos and create an instance of Mongos using an array of Server instances as follows. Not all the Server instances in the array have to be servers that are running and available. For example, we have listed a server at port 50000, but no MongoDB server at port 50000 is running when we run the example.

var mongos = new Mongos([

new Server(“localhost”, 50000),

new Server(“localhost”, 27017)

]);

  1. Create an instance of Db using the Db class constructor with database name as the first argument, the Mongos class instance as the second argument.

var db = new Db(‘local’, mongos);

  1. Open the database using the open() method and in the callback function block list the collections as before.

The db.js script for the Mongos type topology is listed below.

Mongos = require(‘mongodb’).Mongos;

Db = require(‘mongodb’).Db;

Server = require(‘mongodb’).Server;

var mongos = new Mongos([

new Server(“localhost”, 50000),

new Server(“localhost”, 27017)

]);

var db = new Db(‘local’, mongos);

db.open(function(error, db) {

if (error)

console.log(error);

db.listCollections().toArray(function(error, items) {

console.log(items); db.close();

});

});

  1. Run the db.js script to list the collections in the mongodb database as shown in Figure 5-14.

3. Using a Collection

A collection is represented with a Collection class object. The constructor for the Collection class does not take any args, and a new Collection instance may be created with new Collection(). The Collection class provides the properties discussed in Table 5-11.

The Collection constructor is not meant to be invoked directly but is invoked internally. Some of the methods provided by the Collection class are discussed in Table 5-12.

The Db class provides several collection-related methods (collection, collections, createCollection, dropCollection, listCollections, renameCollection) as discussed in Table 5-10. In this section we shall use some of those methods to get, create, rename. and drop a collection and output collection-related information. We already used the listCollections() method in the preceding section.

  1. Create a JavaScript script collection.js in the C:\Program Files\nodejs\ scripts directory.
  2. Import the required classes MongoClient, Server, and Db; some or all of these may be used in creating and accessing a collection based on how the Db instance is created.

MongoClient = require(‘mongodb’).MongoClient;

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

  1. Create a Db instance for the local database as discussed earlier.

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

});

  1. Use the db instance in the callback function block for the open() method to invoke the collections(callback) method. In the callback function block of the collections(callback) method, output information about the collections.

db.collections(function(error, collections){

if (error)

console.log(error);

else{

console.log(“Collections in database local”);

console.log(collections);

}

});

  1. Similarly, use the db instance in the callback function block for the open() method to invoke collection(name, options, callback) method to get the mongodb collection instance. In the callback function block of the collection(name, options, callback) method, output information about the collection such as the collection name, whether the collection capped, and the document count in the collection.

db.collection(‘mongodb’, function(error, collection){

if (error)

console.log(error);

else{

console.log(“Got collection from local database,

collection name: “+collection.collectionName);

collection.isCapped(function(error, result){

console.log(“Is collection capped?: ” +result);

});

collection.count(function(error, result){

console.log(“Document count in the collection: “+result);

});

}

});

  1. Next, create a collection called mongo using the createCollection(name, options, callback) method. Output the collection name using the callback function.

db.createCollection(‘mongo’, function(error, collection){

if (error)

console.log(error);

else{

console.log(“Collection created. Collection name: “+collection. collectionName); }

});

  1. Rename the mongodb collection to mongocoll using the renameCollection (fromCollection, toCollection, options, callback) method. Output the collection name returned in the callback function.

db.renameCollection(‘mongodb’, ‘mongocoll’, function(error,

collection){

if (error)

console.log(error);

else{

console.log(“Collection renamed: “+collection.collectionName);

}

});

  1. Drop the mongocoll collection using the dropCollection(name, callback) method.

db.dropCollection(‘mongocoll’, function(error, result){

if (error)

console.log(error);

else{

console.log(“Collection mongocoll dropped: “+result);

}

});

The collection.js script is listed below.

MongoClient = require(‘mongodb’).MongoClient;

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

db.collections(function(error, collections){

if (error)

console.log(error);

else{

console.log(“Collections in database local”);

console.log(collections);

}

});

db.collection(‘mongodb’, function(error, collection){

if (error)

console.log(error);

else{

console.log(“Got collection from local database, collection name: “+collection.collectionName);

collection.isCapped(function(error, result){

console.log(“Is collection capped?: ” +result);

});

collection.count(function(error, result){ console.log(“Document count in the collection: “+result);

});

}

});

db.createCollection(‘mongo’, function(error, collection){

if (error)

console.log(error);

else{

console.log(“Collection created. Collection name: “+collection. collectionName); }

});

db.renameCollection(‘mongodb’, ‘mongocoll’, function(error, collection){

if (error)

console.log(error);

else{

console.log(“Collection renamed: “+collection.collectionName);

}

});

db.dropCollection(‘mongocoll’, function(error, result){

if (error)

console.log(error);

else{

console.log(“Collection mongocoll dropped: “+result);

}

});

});

  1. Before running the collection.js script create a collection called mongodb in the local database in the Mongo shell as shown in Figure 5-15. If the local database already has the mongodb collection the collection is not required to be created.

  1. Run the collection.js script with the following command.

>node collection.js

The output from the script is shown in Figure 5-16. The script keeps running and to stop the script run Ctrl + C.

We started off with the mongodb collection. Subsequently we created a collection called mongo. We renamed the mongodb collection to mongocoll and subsequently dropped the mongocoll collection. The only collection in the local database other than the startup_log and system.indexes collections is the mongo collection as shown in Figure 5-17.

Source: Vohra Deepak (2015), Pro MongoDB™ Development, Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *