{"id":16651,"library":"mongo-clean","title":"MongoDB Database Cleaner","description":"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.","status":"active","version":"2.0.0","language":"javascript","source_language":"en","source_url":"git://github.com/mcollina/mongo-clean","tags":["javascript","mongodb","clean","test"],"install":[{"cmd":"npm install mongo-clean","lang":"bash","label":"npm"},{"cmd":"yarn add mongo-clean","lang":"bash","label":"yarn"},{"cmd":"pnpm add mongo-clean","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required to connect to and interact with a MongoDB database instance.","package":"mongodb","optional":false}],"imports":[{"note":"The primary export for CommonJS is a default function. Do not use named imports with `require`.","wrong":"import { clean } from 'mongo-clean'","symbol":"clean","correct":"const clean = require('mongo-clean')"},{"note":"For ESM projects, `mongo-clean` typically provides a default export. Do not use named imports with `import`.","wrong":"import { clean } from 'mongo-clean'","symbol":"clean (ESM)","correct":"import clean from 'mongo-clean'"}],"quickstart":{"code":"const clean = require('mongo-clean');\nconst { MongoClient } = require('mongodb');\n\nconst url = \"mongodb://localhost:27017\";\nconst dbName = 'mongocleantest';\n\nasync function run() {\n  let client;\n  try {\n    // Connect to MongoDB using recommended options for modern driver\n    client = await MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });\n    const db = client.db(dbName);\n\n    // Optional: insert some dummy data to demonstrate cleaning\n    await db.collection('users').insertOne({ name: 'Alice' });\n    await db.collection('products').insertOne({ item: 'Laptop' });\n    console.log('Database populated with dummy data (users, products).');\n\n    // Clean the database by dropping collections, excluding 'products'\n    // This will remove the 'users' collection and its data, but 'products' will remain intact.\n    await clean(db, { exclude: ['products'] });\n    console.log('Database cleaned (dropping collections, excluding products).');\n\n    let usersCount = await db.collection('users').countDocuments();\n    let productsCount = await db.collection('products').countDocuments();\n    console.log(`Users collection count: ${usersCount}`); // Should be 0 (collection dropped)\n    console.log(`Products collection count: ${productsCount}`); // Should be 1 (original item still exists in retained collection)\n\n    // Re-populate a collection for the next step demonstration\n    await db.collection('temp_data').insertOne({ value: 123 });\n    console.log('Database re-populated with temporary data for \"remove\" action.');\n\n    // Clean the database by removing documents from all collections\n    // This will empty all collections including 'products' and 'temp_data' (unless explicitly excluded).\n    await clean(db, { action: 'remove' });\n    console.log('Database cleaned by removing documents from all collections.');\n\n    usersCount = await db.collection('users').countDocuments(); // 'users' collection might be recreated if accessed, but will be empty\n    productsCount = await db.collection('products').countDocuments();\n    const tempDataCount = await db.collection('temp_data').countDocuments();\n\n    console.log(`Users collection count after 'remove': ${usersCount}`); // Should be 0\n    console.log(`Products collection count after 'remove': ${productsCount}`); // Should be 0\n    console.log(`Temp Data collection count after 'remove': ${tempDataCount}`); // Should be 0\n\n  } catch (err) {\n    console.error('An error occurred:', err);\n  } finally {\n    if (client) {\n      await client.close();\n      console.log('MongoDB connection closed.');\n    }\n  }\n}\n\nrun();","lang":"javascript","description":"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."},"warnings":[{"fix":"Implement robust environment checks (e.g., `if (process.env.NODE_ENV !== 'production')`) before invoking `mongo-clean` in any application logic that might run in a production context.","message":"Using 'mongo-clean' on a production database can lead to irreversible data loss. Always ensure your connection string or environment variables are configured to target only test or development instances.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Pass `{ action: 'remove' }` as the second argument to the `clean` function for soft clearing: `await clean(db, { action: 'remove' });`","message":"The default 'drop' action completely removes collections, including their indexes, schema, and data. If you need to preserve existing indexes or collection structures while clearing data, use `{ action: 'remove' }`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always include `client.close()` within a `finally` block or ensure your test runner (e.g., Jest, Mocha) handles connection teardown appropriately after tests complete.","message":"Ensure the MongoDB client connection is properly closed after cleaning operations. Failing to do so can lead to resource leaks, prevent your script from exiting, or cause unexpected behavior in testing environments.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer to the `mongodb` driver's release notes for compatibility when updating. Ensure your `mongodb` package version aligns with the version `mongo-clean` was developed against, and update `mongo-clean` if a newer version explicitly supports later `mongodb` drivers.","message":"Breaking changes in the underlying `mongodb` driver (e.g., from v3.x to v4.x or v4.x to v5.x) may affect `mongo-clean`'s ability to interact with the database. While `mongo-clean` itself might not change, its runtime compatibility with the `mongodb` package is crucial.","severity":"breaking","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"For CommonJS, use `const clean = require('mongo-clean');`. For ESM, use `import clean from 'mongo-clean';`","cause":"Incorrect import statement. `mongo-clean` exports a single default function.","error":"TypeError: clean is not a function"},{"fix":"Double-check your MongoDB connection string (`mongodb://user:pass@host:port/dbName`) and ensure the user credentials are valid and have access to the target database.","cause":"The MongoDB connection URL, username, or password provided are incorrect, or the user lacks the necessary authentication for the database.","error":"MongoServerError: Authentication failed."},{"fix":"Grant the MongoDB user appropriate roles (e.g., `dbOwner`, `readWrite`) on the target database or specific collections. For testing, a user with `dbOwner` is often sufficient.","cause":"The authenticated MongoDB user lacks the required permissions to perform `dropCollection` or `deleteMany` operations on the specified database or collections.","error":"MongoServerError: command drop requires authentication"}],"ecosystem":"npm"}