Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop all collections via mongodb and node.js?

I am new to node.js and mongodb and I have the following problem: I need to drop all collections from my mongodb from node.js file. I have such a function:

service.dropCollections = function(db, colls){
  for(var i = 0; i < colls.length; i++){
    var name = colls[i].name;
    db.dropCollection(name, function(err) {
        if(!err) {
            console.log( name + " dropped");
        } else {
            console.log("!ERROR! " + err.errmsg);
        }
    });
  }
}

And I am using it in the following function:

service.clearDB = function() {
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;    

  MongoClient.connect('mongodb://127.0.0.1:27017/shiny_d', 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.showCollections();
    });
  });
}

As an output I have

!ERROR! ns not found

shiny_db.physicalinfos

Dunno what to do right now. I'll be very thankful for your help.

like image 871
Danny Ocean Avatar asked Jul 08 '13 19:07

Danny Ocean


People also ask

How do I drop a collection in MongoDB using node JS?

Drop Collection You can delete a table, or collection as it is called in MongoDB, by using the drop() method. The drop() method takes a callback function containing the error object and the result parameter which returns true if the collection was dropped successfully, otherwise it returns false.

Is it possible to drop database in node JS?

js – Drop Database in MongoDB. We can delete/drop a database from MongoDB through Node. js program.


1 Answers

Ain't it more faster, easier and less error prone if you just drop the entire database?

db.dropDatabase();

At least from the Mongo CLI, whenever you access an inexistent DB, it'll be persisted the soon you create data. That's the same as dropping all collections from it.

I haven't tried MongoDB for anything except studying yet, so I don't know much about permissions. So, probably the only problem of dropping the entire DB would be the permissions of your users that would be lost (I believe).

If this script you're trying to create is not for production, then you're good to go with dropping the DB.

like image 155
gustavohenke Avatar answered Oct 22 '22 23:10

gustavohenke