MongoDB Memory Server for Testing

11.0.1 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

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();
  }
})();

view raw JSON →