Nodejs / mongodb, delete the entire collection

I am trying to delete 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 through mongodb fine:

 db.sessions.remove(); 

What is the best way to achieve what I want through node?

thanks

+4
source share
3 answers

Returning to this ... just to update the question.

 store.collection('sessions',function(err, collection){ collection.remove({},function(err, removed){ }); }); 
+13
source

I know this is a bit late for the party, and a lot has changed, but delete the collection in node , you do it

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

From mongo terminal you do this:

 db.someCollection.drop(); 

It's simple.

+2
source

I'm not sure if you could figure it out, but your code didn't work for me ... maybe due to changes in the API? In any case, I was able to delete the contents of the entire collection using the following code:

 db.CollectionName.remove().exec(function(error) { if(error) { console.log('Uh oh: ' + error); } else { console.log(' [Existing Collection Deleted]'); } }); 
0
source

Source: https://habr.com/ru/post/1380049/


All Articles