docker-mongo

A MongoDB container for Docker Compose, with TypeScript helpers to connect, initialize and seed. Change a setting, and see the connection string and the Compose file change.

Settings, connection string and Compose file

Examples

Environment variables

An empty field is not set, so its default applies. The values stay in your browser.

Connection string connectionUri(settings)
    Resolved config resolveMongoConfig(env)
    SettingValueFrom

    Dry run of init and seed

    The functions initDatabase and seedDatabase do the steps of planInit and planSeed. Edit the input, and see each step as a mongosh command. Nothing connects to a server.

    Steps

      How it works

      1. 1

        Variables to settings

        resolveMongoConfig(process.env) reads eight variables. An empty variable is not set, as in ${VAR:-default} of Compose.

      2. 2

        Settings to a URI

        connectionUri encodes the user and the password. connectionConfig adds the database for withConnection.

      3. 3

        Settings to Compose

        composeFile writes the service. The port opens only on 127.0.0.1, and the file never holds the password.

      4. 4

        Plans to the driver

        initDatabase and seedDatabase do the steps of their plans with the mongodb driver, in sequence.

      The entry @mark1russell7/docker-mongo/pure has steps 1 to 3 and the plans. It imports no driver and no Node.js module, so this page bundles it.

      API

      The page calls each example with the package, and shows the result.

      ExportWhat it doesLive example

      Docker commands

      The shipped docker-compose.yml reads three variables: MONGO_CONTAINER_NAME, MONGO_PORT and MONGO_DB_NAME. For a user or a replica set, save the file of composeFile.

      Start with your settings

      Logs, stop and remove

      docker compose logs -f mongodb
      docker compose down
      # This also removes the volumes, with all the data:
      docker compose down -v

      From your project, after the install

      docker compose -f node_modules/@mark1russell7/docker-mongo/docker-compose.yml up -d

      Install from npm

      npm install @mark1russell7/docker-mongo
      import { connectionConfig, initDatabase, resolveMongoConfig } from "@mark1russell7/docker-mongo";
      
      const { settings, problems } = resolveMongoConfig(process.env);
      if (problems.length > 0) throw new Error(problems.join("\n"));
      
      await initDatabase({
        ...connectionConfig(settings),
        collections: [{ name: "users", indexes: [{ keys: { email: 1 }, options: { unique: true } }] }],
      });

      The package needs Node.js 20 or later, and Docker with Compose for the container.