Registry / database / mongodb-memory-server

mongodb-memory-server

JSON →
library11.0.1jsnpmunverified

MongoDB Memory Server is a robust Node.js library designed to provide a real, in-memory MongoDB server instance for testing purposes, eliminating the need for an external MongoDB installation. It automatically downloads the appropriate MongoDB binary to a local cache directory (`./node_modules/.cache`) upon package installation or first run, ensuring that tests are isolated and reproducible. The current stable version is 11.0.1. The package maintains an active release cadence, frequently pushing patches and minor updates, with major versions typically aligning with significant MongoDB binary version changes or Node.js LTS updates. It's particularly useful for integration tests, allowing developers to connect their preferred ODM (like Mongoose or Typegoose) or client library to a fresh, isolated MongoDB instance for each test suite, thereby preventing state leakage between tests and speeding up CI/CD pipelines.

npm install mongodb-memory-server
INSTALL
IMPORT
SIG · MONGODB-MEMORY-SER
M
mongodb-memory-server
databasejavascriptv11.0.1
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.

MongoMemoryServer
import { MongoMemoryServer } from 'mongodb-memory-server';
const MongoMemoryServer = require('mongodb-memory-server');
While CommonJS `require` still works, modern Node.js environments (v20+) and TypeScript projects primarily use ES Modules. Since v11, the `tsconfig` target is `es2023`, favoring ESM.
MongoMemoryReplSet
import { MongoMemoryReplSet } from 'mongodb-memory-server';
import MongoMemoryReplSet from 'mongodb-memory-server/MongoMemoryReplSet';
Both `MongoMemoryServer` and `MongoMemoryReplSet` are named exports from the main package entry point.
start
await mongoServer.start();
mongoServer.start(); // Missing await
All lifecycle methods (`start`, `stop`, `getUri`) return Promises and must be awaited to ensure proper sequencing and avoid race conditions or undefined URIs.

This quickstart demonstrates how to initialize, connect to, perform a basic operation, and cleanly shut down a MongoDB Memory Server instance using the official `mongodb` driver.

import { MongoMemoryServer } from 'mongodb-memory-server'; import { MongoClient } from 'mongodb'; let mongoServer: MongoMemoryServer; let client: MongoClient; async function setupDatabase() { mongoServer = await MongoMemoryServer.create(); const mongoUri = mongoServer.getUri(); client = new MongoClient(mongoUri); await client.connect(); console.log(`Connected to MongoDB at ${mongoUri}`); const db = client.db('testdb'); const collection = db.collection('documents'); await collection.insertOne({ a: 1 }); const doc = await collection.findOne({ a: 1 }); console.log('Inserted and found document:', doc); } async function teardownDatabase() { if (client) { await client.close(); console.log('MongoDB client closed.'); } if (mongoServer) { await mongoServer.stop(); console.log('MongoDB Memory Server stopped.'); } } (async () => { try { await setupDatabase(); } catch (error) { console.error('Database operation failed:', error); } finally { await teardownDatabase(); } })();
Debug
Known issues
breakingThe default MongoDB binary version downloaded by `mongodb-memory-server` has been upgraded to 8.2.x.
fix
If you require an older MongoDB version for compatibility, you must explicitly configure it using the `binary.version` option in the `MongoMemoryServer` constructor or via environment variables (e.g., `MONGODB_VERSION=7.0.x`).
affects: >=11.0.0
breakingNode.js 20.19.0 is now the lowest supported version. Running on older Node.js versions will result in errors.
fix
Upgrade your Node.js environment to version 20.19.0 or higher. Check your `engines` field in `package.json` and CI/CD configurations.
affects: >=11.0.0
breakingSupport for MongoDB binary versions below 4.2.0 has been removed. The `-global-4.0` package is also unsupported.
fix
Ensure your tests are compatible with MongoDB 4.2.0 or newer. If testing legacy MongoDB features is necessary, you will need to stick to `mongodb-memory-server` v10.x or earlier.
affects: >=11.0.0
breakingThe `tsconfig` target has been updated to `es2023`, which may introduce compilation issues or require adjustments in older TypeScript projects.
fix
Update your project's `tsconfig.json` to target `es2023` or higher, or ensure your TypeScript compiler (`tsc`) version is up-to-date and compatible with `es2023` features.
affects: >=11.0.0
gotchaDownloading the MongoDB binary can fail or be slow due to network restrictions, proxies, or antivirus software.
fix
Configure proxy settings via environment variables (e.g., `HTTP_PROXY`, `HTTPS_PROXY`), increase download timeouts (`DOWNLOAD_TIMEOUT`), or pre-fetch the binary manually if running in an air-gapped environment. Ensure firewalls are not blocking the download URLs.
affects: >=1.0.0
Errors
Common errors & fixes
Error: MongoNetworkError: connect ECONNREFUSED
The MongoDB Memory Server failed to start, or your application tried to connect before it was ready.
fix
Ensure you `await mongoServer.start()` before attempting to connect your client or ODM. Check the console for any errors during the `start()` process indicating binary download or startup issues.
MongoServerError: Command 'replSetGetStatus' not found
You are trying to execute a replica set-specific command on a single `MongoMemoryServer` instance.
fix
If your application requires replica set functionality (e.g., transactions, change streams), you must use `MongoMemoryReplSet` instead of `MongoMemoryServer`. Initialize with `new MongoMemoryReplSet()` and configure appropriate replica set options.
Error: Mongod not found
The MongoDB binary could not be downloaded or found in the expected cache location.
fix
Verify your network connectivity and proxy settings. Check the `--debug` flag or `DEBUG=mongodb-memory-server:*` environment variable for detailed download logs. You might also need to clear the cache (`npm cache clean --force` or manually delete `.cache` directory) and reinstall.
Upgrade
Version history
11.0.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources
mongodb-memory-server — npm install mongodb-memory-server · libregistry