Collection Creation, Listing, and Deleting Example

To illustrate the process of creating, listing, and deleting collections, Listing 13.5 makes a series of chained callbacks that list the collections, create a new collection, and then delete the new collection. The code is very basic and easy to follow. Figure 13.5 shows the output.

Listing 13.5 collection_create_list_delete.js: Creating, retrieving, and deleting collections on a MongoDB database


01 var MongoClient = require('mongodb').MongoClient;
02 MongoClient.connect("mongodb://localhost/", function(err, db) {
03   var newDB = db.db("newDB");
04   newDB.collectionNames(function(err, collectionNames){
05     console.log("Initial collections: ");
06     console.log(collectionNames);
07     newDB.createCollection("newCollection", function(err, collection){
08       newDB.collectionNames(function(err, collectionNames){
09         console.log("Collections after creation: ");
10         console.log(collectionNames);
11         newDB.dropCollection("newCollection", function(err, results){
12           newDB.collectionNames(function(err, collectionNames){
13             console.log("Collections after deletion: ");
14             console.log(collectionNames);
15             db.close();
16           });
17         });
18       });
19     });
20   });
21 });


Image

Figure 13.5 Creating, retrieving, and deleting collections on a MongoDB database.

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

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