Why I use mongodb-memory-server

Why I use mongodb-memory-server

Introduction

As a backend developer, testing your code is an essential part of ensuring that your application is robust and running smoothly. One of the most popular databases for backend development is MongoDB.

However, running MongoDB in a testing environment can be challenging, as it requires a running database server. This is where the mongodb-memory-server package comes in handy.

What is mongodb-memory-server?

The mongodb-memory-server package provides an in-memory MongoDB database for testing. This package is particularly useful for unit tests, where you don't want to rely on an external MongoDB server.

Instead, the mongodb-memory-server package allows you to spin up a local MongoDB instance programmatically, making it easy to test your code in a controlled environment.

Docs: https://github.com/nodkz/mongodb-memory-server

Benefits of Using mongodb-memory-server for Testing

Benefit #1

Using the mongodb-memory-server package is that it eliminates the need for an external database server.

This means that you can run your tests locally, without having to worry about connecting to a remote server or setting up a local instance.

Additionally, because the database is in-memory, it is much faster than a traditional MongoDB server, which can be particularly useful for testing performance-sensitive code.

Benefit #2

It makes it easy to create and destroy test data. With a traditional MongoDB server, you would need to manually create and manage test data, which can be time-consuming and error-prone.

However, with the mongodb-memory-server package, you can programmatically create and destroy data, making it easy to set up your test environment and clean up after your tests are complete.

Getting Started with mongodb-memory-server

Getting started with the mongodb-memory-server package is straightforward. First, you will need to install the package via npm.

npm i mongodb-memory-server

Once installed, you can import the package into your test setup file and use it to create an in-memory MongoDB instance. You can create several instances of MongoDB, but only limited by the space in your RAM.

// setup.js for jest tests

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

let mongo;

beforeAll(async () => {
    // create an instance of MongoDB In-Memory Server
    mongo = await MongoMemoryServer.create();

    // URI of that instance, which can then be used to connect to the MongoDB server
    const mongoUri = mongo.getUri();

    // connecting to In-Memory MongoDB Server
    await mongoose.connect(mongoUri, {});
})

// clean data before every test
beforeEach(async () => {

    const collections = await mongoose.connection.db.collections();

    for (let collection of collections) {
        await collection.deleteMany({});
    }
})

afterAll(async () => {

    if (mongo)
        await mongo.stop();

    await mongoose.connection.close();
})

Also, remember to specify the path to the setup.js file in the jest configuration

"jest": {
    "testEnvironment": "node",
    "setupFilesAfterEnv": [
      "path/to/setup.ts"
    ],
    "testTimeout": 60000
  },

Available Options for MongoMemoryServer

const mongod = new MongoMemoryServer({
  instance: {
    port?: number, // by default choose any free port
    ip?: string, // by default '127.0.0.1', for binding to all IP addresses set it to `::,0.0.0.0`,
    dbName?: string, // by default '' (empty string)
    dbPath?: string, // by default create in temp directory
    storageEngine?: string, // by default `ephemeralForTest`, available engines: [ 'ephemeralForTest', 'wiredTiger' ]
    replSet?: string, // by default no replica set, replica set name
    auth?: boolean, // by default `mongod` is started with '--noauth', start `mongod` with '--auth'
    args?: string[], // by default no additional arguments, any additional command line arguments for `mongod` `mongod` (ex. ['--notablescan'])
  },
  binary: {
    version?: string, // by default '5.0.13'
    downloadDir?: string, // by default node_modules/.cache/mongodb-memory-server/mongodb-binaries
    platform?: string, // by default os.platform()
    arch?: string, // by default os.arch()
    checkMD5?: boolean, // by default false OR process.env.MONGOMS_MD5_CHECK
    systemBinary?: string, // by default undefined or process.env.MONGOMS_SYSTEM_BINARY
  },
});

Summary

  1. Easy to set up: Setting up MongoDB Memory Server is very easy. You can install it via npm and then use it in your Node.js project.

  2. In-memory database: MongoDB Memory Server runs an in-memory MongoDB database, which means that all data is stored in RAM and not on disk. This makes it very fast and efficient for testing.

  3. No need for separate MongoDB installation: Since MongoDB Memory Server is an in-memory database, you do not need to install a separate MongoDB instance on your machine to use it.

  4. Supports all MongoDB features: MongoDB Memory Server supports all the features of MongoDB, including indexing, aggregation, and transactions.

  5. Customizable configuration: You can customize the configuration of the MongoDB Memory Server to meet your specific testing needs. For example, you can set the database name, port number, and other settings.

  6. Cross-platform support: MongoDB Memory Server supports all major operating systems, including Windows, macOS, and Linux.

  7. Helpful documentation and community: MongoDB Memory Server has helpful documentation and an active community that can help you get started and answer any questions you may have.
    API Docs:

    https://nodkz.github.io/mongodb-memory-server/docs/api/index-api/

Did you find this article valuable?

Support Mayukh Bhowmick by becoming a sponsor. Any amount is appreciated!