Registry / database / mongo-clean

mongo-clean

JSON →
library2.0.0jsnpmunverified

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-clean
INSTALL
IMPORT
SIG · MONGO-CLEAN
M
mongo-clean
databasejavascriptv2.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

clean
const clean = require('mongo-clean')
import { clean } from 'mongo-clean'
The primary export for CommonJS is a default function. Do not use named imports with `require`.
clean (ESM)
import clean from 'mongo-clean'
import { clean } from 'mongo-clean'
For ESM projects, `mongo-clean` typically provides a default export. Do not use named imports with `import`.

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();
Debug
Known issues
gotchaUsing '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.
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.
affects: >=1.0.0
gotchaThe 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' }`.
fix
Pass `{ action: 'remove' }` as the second argument to the `clean` function for soft clearing: `await clean(db, { action: 'remove' });`
affects: >=1.0.0
gotchaEnsure 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.
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.
affects: >=1.0.0
breakingBreaking 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.
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.
affects: >=2.0.0
Errors
Common errors & fixes
TypeError: clean is not a function
Incorrect import statement. `mongo-clean` exports a single default function.
fix
For CommonJS, use `const clean = require('mongo-clean');`. For ESM, use `import clean from 'mongo-clean';`
MongoServerError: Authentication failed.
The MongoDB connection URL, username, or password provided are incorrect, or the user lacks the necessary authentication for the database.
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.
MongoServerError: command drop requires authentication
The authenticated MongoDB user lacks the required permissions to perform `dropCollection` or `deleteMany` operations on the specified database or collections.
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.
Upgrade
Version history
2.0.0latest on npm
Audit
Dependencies
mongodbrequiredRequired to connect to and interact with a MongoDB database instance.
Agent activity
8 hits · last 30 days
node
8
Resources
mongo-clean — npm install mongo-clean · libregistry