MongoDB Database Cleaner

2.0.0 · active · verified Wed Apr 22

mongo-clean is a focused utility designed to efficiently clear data from MongoDB databases, primarily used in testing or development environments. Version 2.0.0 is the current stable release. It offers two main strategies for cleaning: dropping entire collections or removing all documents within them, providing flexibility depending on schema requirements or performance considerations. A key feature is the ability to exclude specific collections from the cleaning process, preventing accidental data loss for essential tables. It supports both traditional callback-based asynchronous operations and modern Promise-based and `async/await` syntax, integrating seamlessly into contemporary Node.js applications. The package's minimalist API distinguishes it from more complex database management tools, focusing solely on the clean-up task. Its release cadence is not explicitly stated, but its clear purpose suggests a mature, low-churn library.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to MongoDB, populating dummy data, cleaning the database by dropping collections (with exclusions), and then cleaning by removing documents from all collections, illustrating both primary cleaning methods and proper client closure.

const clean = require('mongo-clean');
const { MongoClient } = require('mongodb');

const url = "mongodb://localhost:27017";
const dbName = 'mongocleantest';

async function run() {
  let client;
  try {
    // Connect to MongoDB using recommended options for modern driver
    client = await MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
    const db = client.db(dbName);

    // Optional: insert some dummy data to demonstrate cleaning
    await db.collection('users').insertOne({ name: 'Alice' });
    await db.collection('products').insertOne({ item: 'Laptop' });
    console.log('Database populated with dummy data (users, products).');

    // Clean the database by dropping collections, excluding 'products'
    // This will remove the 'users' collection and its data, but 'products' will remain intact.
    await clean(db, { exclude: ['products'] });
    console.log('Database cleaned (dropping collections, excluding products).');

    let usersCount = await db.collection('users').countDocuments();
    let productsCount = await db.collection('products').countDocuments();
    console.log(`Users collection count: ${usersCount}`); // Should be 0 (collection dropped)
    console.log(`Products collection count: ${productsCount}`); // Should be 1 (original item still exists in retained collection)

    // Re-populate a collection for the next step demonstration
    await db.collection('temp_data').insertOne({ value: 123 });
    console.log('Database re-populated with temporary data for "remove" action.');

    // Clean the database by removing documents from all collections
    // This will empty all collections including 'products' and 'temp_data' (unless explicitly excluded).
    await clean(db, { action: 'remove' });
    console.log('Database cleaned by removing documents from all collections.');

    usersCount = await db.collection('users').countDocuments(); // 'users' collection might be recreated if accessed, but will be empty
    productsCount = await db.collection('products').countDocuments();
    const tempDataCount = await db.collection('temp_data').countDocuments();

    console.log(`Users collection count after 'remove': ${usersCount}`); // Should be 0
    console.log(`Products collection count after 'remove': ${productsCount}`); // Should be 0
    console.log(`Temp Data collection count after 'remove': ${tempDataCount}`); // Should be 0

  } catch (err) {
    console.error('An error occurred:', err);
  } finally {
    if (client) {
      await client.close();
      console.log('MongoDB connection closed.');
    }
  }
}

run();

view raw JSON →