Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs/mongodb, remove entire collection

I'm trying to remove all items in a collection.

db.collection('sessions', function(err, collection) {                                      
    collection.remove();                 
});

This is the error I get:

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
TypeError: Cannot call method 'getRequestId' of null
    at [object Object].executeCommand (/srv/www/www.cidev.com/nodejs/node_modules/mongodb/lib/mongodb/db.js:778:48)
    at Collection.remove (/srv/www/www.cidev.com/nodejs/node_modules/mongodb/lib/mongodb/collection.js:199:26)
    at /srv/www/www.cidev.com/nodejs/session/memory/index.js:15:20
    at [object Object].collection (/srv/www/www.cidev.com/nodejs/node_modules/mongodb/lib/mongodb/db.js:197:12)
    at new <anonymous> (/srv/www/www.cidev.com/nodejs/session/memory/index.js:14:11)
    at Object.<anonymous> (/srv/www/www.cidev.com/nodejs/session/memory/index.js:157:16)
    at Module._compile (module.js:411:26)
    at Object..js (module.js:417:10)
    at Module.load (module.js:343:31)
    at Function._load (module.js:302:12)

However, I can do this via mongodb fine:

db.sessions.remove();

What's the best way to achieve what I want via node?

Thanks

like image 875
PaulM Avatar asked Nov 07 '11 19:11

PaulM


3 Answers

I know this is a little late to the party and much has changed, but to remove a collection in node, you do this:

db.collection('someCollection').drop();

From the mongo terminal you do this:

db.someCollection.drop();

It's that simple.

like image 52
The Qodesmith Avatar answered Oct 13 '22 16:10

The Qodesmith


Providing a more recent answer, based on API changes and trying the previous answers myself.

The following example represents a block of code as we use it in our integration tests:

const mongoUrl = 'mongodb://localhost:27017/test-database';
const mongoClient = await MongoClient.connect(mongoUrl, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const database = mongoClient.db();
if (database) {
  const collections = await database.listCollections();
  await collections.forEach(async collection => {
    console.log(`Dropping ${collection.name}`);
    await database.collection(collection.name).drop();
  });
}

Note, while you could use the following, it will fail if you don't have full permissions over the database, such as in Mongo Cloud:

await database.dropDatabase();

For context, I was using mongodb package 3.5.9 and node 14.15.1.

like image 21
Andre M Avatar answered Oct 13 '22 17:10

Andre M


Going back to this... just to update the question.

store.collection('sessions',function(err, collection){
    collection.remove({},function(err, removed){
    });
});
like image 43
PaulM Avatar answered Oct 13 '22 18:10

PaulM