0

I want to create a script which is going to delete documents in collections but remain the collection itself (just make 0 documents inside a collection). When I run the script with node it just runs but didn't do anything at all. No errors.

Code:

var mongoClient = require('mongodb').MongoClient;

var url = 'mongodb+srv://username:[email protected]/<dbname>?retryWrites=true&w=majority';

mongoClient.connect(url, { useUnifiedTopology: true }, function(err, db) {
    if (err) {
        console.log('Sorry unable to connect to MongoDB Error:', err);
    } else {

        async function deleteListingsScrapedBeforeDate() {
            result = await client.db("CryptoCurrencies").collection("who")
                .remove({});
            console.log(`${result.deletedCount} document(s) was/were deleted.`);
            await deleteListingsScrapedBeforeDate();
        }
    }

});

Also is there a way to have a script which is going to delete all documents in multiple collections? Can I declare a collections like an array?

1
  • What documentation are you following? Commented Jun 30, 2020 at 13:13

1 Answer 1

1

In the above code the function deleteListingsScrapedBeforeDate() is never actually called (also if it were called this would result in an endless recursion). You should change this to:

const MongoClient = require('mongodb').MongoClient;

async function deleteListingsScrapedBeforeDate(db) {
   await db.collection("who").remove({});
   console.log(`${result.deletedCount} document(s) was/were deleted.`);            
}

(async function() {

  const url = 'mongodb+srv://username:[email protected]/<dbname>?retryWrites=true&w=majority';

  const dbName = '<dbname>';
  let client;

  try {

    client = await MongoClient.connect(url);    
    const db = client.db(dbName);
    await deleteListingsScrapedBeforeDate(db);
    
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
Sign up to request clarification or add additional context in comments.

1 Comment

Damn, my bad, was totally done after day of coding. Thank you for solution, that's working one. Help's me a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.