MongoDB Memory Server Global

11.0.1 · active · verified Sun Apr 19

MongoDB Memory Server Global (mongodb-memory-server-global) provides a convenient, pre-configured way to set up and manage an in-memory MongoDB instance for testing and development. As of version 11.0.1, it automates the download and caching of the latest MongoDB server binaries (defaulting to 8.2.x since v11) to a user's local cache directory (`~/.cache/mongodb-binaries`) upon installation. This package acts primarily as an installation wrapper, simplifying the environment setup for its counterpart, `mongodb-memory-server`, which offers the actual programmatic API to start, stop, and manage the in-memory database instances. It aims for a stable release cadence, with patch and minor updates released frequently, and major versions introducing significant breaking changes and updated MongoDB defaults. Key differentiators include its ease of setup for CI/CD environments and its ability to quickly spin up isolated database instances without requiring a pre-installed MongoDB server.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates starting an in-memory MongoDB instance, connecting with Mongoose, performing basic CRUD operations, and then cleaning up the connection and server. This setup implicitly relies on `mongodb-memory-server-global` having pre-downloaded the necessary binaries.

import { MongoMemoryServer } from 'mongodb-memory-server';
import mongoose from 'mongoose';

async function runInMemoryDbTest() {
  // mongodb-memory-server-global ensures binaries are available.
  // MongoMemoryServer handles the in-memory instance.
  const mongod = await MongoMemoryServer.create();
  const uri = mongod.getUri();

  console.log(`MongoDB Memory Server started at: ${uri}`);

  try {
    await mongoose.connect(uri);
    console.log('Mongoose connected to in-memory MongoDB');

    const UserSchema = new mongoose.Schema({ name: String, email: String });
    const User = mongoose.model('User', UserSchema);

    const newUser = await User.create({ name: 'Test User', email: 'test@example.com' });
    console.log('User created:', newUser);

    const foundUser = await User.findOne({ name: 'Test User' });
    console.log('User found:', foundUser);

  } catch (error) {
    console.error('Error during test:', error);
  } finally {
    await mongoose.disconnect();
    console.log('Mongoose disconnected.');
    await mongod.stop();
    console.log('MongoDB Memory Server stopped.');
  }
}

runInMemoryDbTest();

view raw JSON →