MongoDB Memory Server for Testing
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.
Common errors
-
Error: MongoNetworkError: connect ECONNREFUSED
cause The MongoDB Memory Server failed to start, or your application tried to connect before it was ready.fixEnsure 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
cause You are trying to execute a replica set-specific command on a single `MongoMemoryServer` instance.fixIf 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
cause The MongoDB binary could not be downloaded or found in the expected cache location.fixVerify 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.
Warnings
- breaking The default MongoDB binary version downloaded by `mongodb-memory-server` has been upgraded to 8.2.x.
- breaking Node.js 20.19.0 is now the lowest supported version. Running on older Node.js versions will result in errors.
- breaking Support for MongoDB binary versions below 4.2.0 has been removed. The `-global-4.0` package is also unsupported.
- breaking The `tsconfig` target has been updated to `es2023`, which may introduce compilation issues or require adjustments in older TypeScript projects.
- gotcha Downloading the MongoDB binary can fail or be slow due to network restrictions, proxies, or antivirus software.
Install
-
npm install mongodb-memory-server -
yarn add mongodb-memory-server -
pnpm add mongodb-memory-server
Imports
- MongoMemoryServer
const MongoMemoryServer = require('mongodb-memory-server');import { MongoMemoryServer } from 'mongodb-memory-server'; - MongoMemoryReplSet
import MongoMemoryReplSet from 'mongodb-memory-server/MongoMemoryReplSet';
import { MongoMemoryReplSet } from 'mongodb-memory-server'; - start
mongoServer.start(); // Missing await
await mongoServer.start();
Quickstart
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();
}
})();