I have found the answer. First of all, I made a mistake in my connection, it should look like this: 'mongodb://127.0.0.1:27017/shiny_db' . The second mistake was in the name of the collection. It was like 'db_name.coll_name' , so db.dropCollection(name, callback) could not find a specific collection, and because of this I was wrong ns not found . Therefore, I used the following mechanism to separate db_name from coll_name:
var name = colls[i].name.substring('shiny_db.'.length); , and I added a check for the "system" collection.
The resulting code is as follows:
service.clearDB = function() { var MongoClient = require('mongodb').MongoClient , format = require('util').format; MongoClient.connect('mongodb://localhost/shiny_db', function(err, db) { if(err) throw err; db.collectionNames(function(err, collections){ if(!err){ service.dropCollections(db, collections); } else { console.log("!ERROR! "+ err.errmsg); } }); }); } service.dropCollections = function(db, colls){ for(var i = 0; i < colls.length; i++){ var name = colls[i].name.substring('shiny_db.'.length); if (name.substring(0, 6) !== "system") { db.dropCollection(name, function(err) { if(!err) { console.log( name + " dropped"); } else { console.log("!ERROR! " + err.errmsg); } }); } else { console.log(name + " cannot be dropped because it a system file"); } } }
Hope this helps someone!
Danny ocean
source share