Creating, Listing, and Deleting Databases Example

To help solidify the database operations, Listing 13.3 illustrates the full process of creating, listing, and deleting databases. A connection is made to the MongoDB server, and then lines 4–7 list the current databases. Then lines 8 and 9 create a new database by calling create-Collection(). Inside the createCollection() callback handler, the databases are listed again to verify creation.

Lines 15–32 delete the database by using dropDatabase(). Notice that inside the drop-Database() callback, a setTimeout() timer is implemented to wait for a number of seconds before checking the list of databases to verify that the database was deleted. The output is shown in Figure 13.3.

Listing 13.3 db_create_list_delete.js: Creating, listing, and deleting databases, using the MongoDB Node.js driver


01 var MongoClient = require('mongodb').MongoClient;
02 MongoClient.connect("mongodb://localhost/", function(err, db) {
03   var adminDB = db.admin();
04   adminDB.listDatabases(function(err, databases){
05     console.log("Before Add Database List: ");
06     console.log(databases);
07   });
08   var newDB = db.db("newDB");
09   newDB.createCollection("newColleciton", function(err, collection){
10     if(!err){
11       console.log("New Database and Collection Created");
12       adminDB.listDatabases(function(err, databases){
13         console.log("After Add Database List: ");
14         console.log(databases);
15         db.db("newDB").dropDatabase(function(err, results){
16           if(!err){
17             console.log("Database dropped.");
18             setTimeout(function() {
19               adminDB.listDatabases(function(err, results){
20                 var found = false;
21                 for(var i = 0; i < results.databases.length; i++) {
22                   if(results.databases[i].name == "newDB") found = true;
23                 }
24                 if (!found){
25                   console.log("After Delete Database List: ");
26                   console.log(results);
27                 }
28                 db.close();
29               });
30             }, 15000);
31           }
32         });
33       });
34     }
35   });
36 });


Image

Figure 13.3 Creating, listing, and deleting databases using the MongoDB Node.js driver.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.152.166