{"id":11359,"library":"mongodb-memory-server","title":"MongoDB Memory Server for Testing","description":"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.","status":"active","version":"11.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/typegoose/mongodb-memory-server","tags":["javascript","mongodb","mongoose","mock","stub","mockgoose","mongodb-prebuilt","mongomem","typescript"],"install":[{"cmd":"npm install mongodb-memory-server","lang":"bash","label":"npm"},{"cmd":"yarn add mongodb-memory-server","lang":"bash","label":"yarn"},{"cmd":"pnpm add mongodb-memory-server","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"const MongoMemoryServer = require('mongodb-memory-server');","symbol":"MongoMemoryServer","correct":"import { MongoMemoryServer } from 'mongodb-memory-server';"},{"note":"Both `MongoMemoryServer` and `MongoMemoryReplSet` are named exports from the main package entry point.","wrong":"import MongoMemoryReplSet from 'mongodb-memory-server/MongoMemoryReplSet';","symbol":"MongoMemoryReplSet","correct":"import { MongoMemoryReplSet } from 'mongodb-memory-server';"},{"note":"All lifecycle methods (`start`, `stop`, `getUri`) return Promises and must be awaited to ensure proper sequencing and avoid race conditions or undefined URIs.","wrong":"mongoServer.start(); // Missing await","symbol":"start","correct":"await mongoServer.start();"}],"quickstart":{"code":"import { MongoMemoryServer } from 'mongodb-memory-server';\nimport { MongoClient } from 'mongodb';\n\nlet mongoServer: MongoMemoryServer;\nlet client: MongoClient;\n\nasync function setupDatabase() {\n  mongoServer = await MongoMemoryServer.create();\n  const mongoUri = mongoServer.getUri();\n  client = new MongoClient(mongoUri);\n  await client.connect();\n  console.log(`Connected to MongoDB at ${mongoUri}`);\n\n  const db = client.db('testdb');\n  const collection = db.collection('documents');\n\n  await collection.insertOne({ a: 1 });\n  const doc = await collection.findOne({ a: 1 });\n  console.log('Inserted and found document:', doc);\n}\n\nasync function teardownDatabase() {\n  if (client) {\n    await client.close();\n    console.log('MongoDB client closed.');\n  }\n  if (mongoServer) {\n    await mongoServer.stop();\n    console.log('MongoDB Memory Server stopped.');\n  }\n}\n\n(async () => {\n  try {\n    await setupDatabase();\n  } catch (error) {\n    console.error('Database operation failed:', error);\n  } finally {\n    await teardownDatabase();\n  }\n})();","lang":"typescript","description":"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."},"warnings":[{"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`).","message":"The default MongoDB binary version downloaded by `mongodb-memory-server` has been upgraded to 8.2.x.","severity":"breaking","affected_versions":">=11.0.0"},{"fix":"Upgrade your Node.js environment to version 20.19.0 or higher. Check your `engines` field in `package.json` and CI/CD configurations.","message":"Node.js 20.19.0 is now the lowest supported version. Running on older Node.js versions will result in errors.","severity":"breaking","affected_versions":">=11.0.0"},{"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.","message":"Support for MongoDB binary versions below 4.2.0 has been removed. The `-global-4.0` package is also unsupported.","severity":"breaking","affected_versions":">=11.0.0"},{"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.","message":"The `tsconfig` target has been updated to `es2023`, which may introduce compilation issues or require adjustments in older TypeScript projects.","severity":"breaking","affected_versions":">=11.0.0"},{"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.","message":"Downloading the MongoDB binary can fail or be slow due to network restrictions, proxies, or antivirus software.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","cause":"The MongoDB Memory Server failed to start, or your application tried to connect before it was ready.","error":"Error: MongoNetworkError: connect ECONNREFUSED"},{"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.","cause":"You are trying to execute a replica set-specific command on a single `MongoMemoryServer` instance.","error":"MongoServerError: Command 'replSetGetStatus' not found"},{"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.","cause":"The MongoDB binary could not be downloaded or found in the expected cache location.","error":"Error: Mongod not found"}],"ecosystem":"npm"}