MongoDB Database Cleaner
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
-
TypeError: clean is not a function
cause Incorrect import statement. `mongo-clean` exports a single default function.fixFor CommonJS, use `const clean = require('mongo-clean');`. For ESM, use `import clean from 'mongo-clean';` -
MongoServerError: Authentication failed.
cause The MongoDB connection URL, username, or password provided are incorrect, or the user lacks the necessary authentication for the database.fixDouble-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. -
MongoServerError: command drop requires authentication
cause The authenticated MongoDB user lacks the required permissions to perform `dropCollection` or `deleteMany` operations on the specified database or collections.fixGrant 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.
Warnings
- gotcha 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.
- gotcha 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' }`.
- gotcha 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.
- breaking 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.
Install
-
npm install mongo-clean -
yarn add mongo-clean -
pnpm add mongo-clean
Imports
- clean
import { clean } from 'mongo-clean'const clean = require('mongo-clean') - clean (ESM)
import { clean } from 'mongo-clean'import clean from 'mongo-clean'
Quickstart
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();