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.
npm install mongo-cleanVerified import paths — ran on the pinned version, not inferred.
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.
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.
Pass `{ action: 'remove' }` as the second argument to the `clean` function for soft clearing: `await clean(db, { action: 'remove' });`Always include `client.close()` within a `finally` block or ensure your test runner (e.g., Jest, Mocha) handles connection teardown appropriately after tests complete.
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.
For CommonJS, use `const clean = require('mongo-clean');`. For ESM, use `import clean from 'mongo-clean';`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.
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.