npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bitscheme/mgdb-migrator

v4.0.2

Published

Mongodb schema and data migration lib

Downloads

44

Readme

A simple migration system for mongodb supporting up/downwards migrations.

Status

| Branch | Status | | ------ | :-----------------------------------------------------------------------------------------------------------: | | Next | CI Workflow | | Master | CI Workflow |

Install

$ npm i mgdb-migrator

or

$ yarn add mgdb-migrator

Quick Start

import { migrator } from 'mgdb-migrator'

await migrator.config({
  // false disables logging
  log: true,
  // optional logging function
  logger: (level, ...args) => console.log(level, ...args),
  // migrations collection name defaults to 'migrations'
  collectionName: 'migrations',
  // max time allowed in ms for a migration to finish, default Number.POSITIVE_INFINITY
  timeout: 30000,
  // connection properties object
  db: {
    // mongodb connection url
    connectionUrl: 'mongodb://localhost:27017/my-db',
    // optional database name, in case using it in connection string is not an option
    name: 'my-db',
    // optional mongodb MongoClientOptions
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }
  }
})

migrator.add({
  version: 1,
  name: 'Name for this migration',
  up: async (client: MongoClient, logger: Logger) => {
    // write your migration here
    await client
      .db()
      .collection('albums')
      .updateMany({}, { $set: { stars: 5 } })
  },
  down: async (client: MongoClient, logger: Logger) => {
    // write your reverting migration here
    await client
      .db()
      .collection('albums')
      .updateMany({}, { $set: { stars: 0 } })
  }
})

// run all configured migrations greater than the current version in order
await migrator.up()

Versioning

Migration versions use sequential integers. Version 0 is reserved by migrator for initial state to indicate no migrations have been applied.

Flow

Migration state is implemented in the MongoDB collection migrations. It contains a single document used for locking migration control. Only one set of migrations is allowed to execute at a time.

You can override the collection name in config if needed.

{
  _id: String, // 'control'
  version: Int32,
  locked: Bool,
  lockedAt: Date
}

When a migration is performed, all migrations that include versions between current and target are executed serially in order.

For example, if you have added the following migrations:

  • v1
  • v2
  • v3
  • v4

and the current version is at v0, executing up(3) will run migrations v1, v2 and v3. If all migrations were successful, the current version becomes v3.

If any particular migration rejects or throws an error, subsequent migrations are halted and the current version is set to the last successfully completed migration.

API

config(opts: IMigrationOptions) ⇒ Promise<void>

See the Quick Start for options.

add(migration: IMigration)

To setup a new database migration script, call migrator.add.

You must implement up and down functions. Return a promise (or use async/await) and resolve to indicate success, throw an error or reject to abort.

up(target?: number) ⇒ Promise<void>

To migrate to the latest configured migration:

migrator.up()

Or by specifying a target version, you can migrate directly to that version (if possible).

migrator.up(1)

down(target: number) ⇒ Promise<void>

To revert a migration:

migrator.down(1)

If you want to undo all of your migrations, you can migrate back down to version 0 by running:

migrator.down(0)

Sometimes (usually when something goes awry), you may need to retry a migration. You can do this by updating the migrations.version field in mongodb to the previous version and re-executing your migration.

getVersion() ⇒ number

To see what version the database is at, call:

migrator.getVersion()

getMigrations() ⇒ IMigration[]

To see the configured migrations (excluding v0), call:

migrator.getMigrations()

close(force?: boolean) ⇒ Promise<void>

To close the mongodb connection, call:

migrator.close()

Using MongoDB Transactions API

You can make use of the MongoDB Transaction API in your migration scripts.

Note: this requires

  • MongoDB 4.0 or higher

migrator will call your migration up and down function with a second argument: client, a MongoClient instance to give you access to the startSession function.

Example:

const albumMigration = {
  version: 1,
  async up(client) {
    const session = client.startSession()
    try {
      await session.withTransaction(async () => {
        await db
          .collection('albums')
          .updateOne({ artist: 'The Beatles' }, { $set: { blacklisted: true } })
        await db.collection('albums').updateOne({ artist: 'The Doors' }, { $set: { stars: 5 } })
      })
    } finally {
      await session.endSession()
    }
  },
  async down(client) {
    const session = client.startSession()
    try {
      await session.withTransaction(async () => {
        await db
          .collection('albums')
          .updateOne({ artist: 'The Beatles' }, { $set: { blacklisted: false } })
        await db.collection('albums').updateOne({ artist: 'The Doors' }, { $set: { stars: 0 } })
      })
    } finally {
      await session.endSession()
    }
  }
}

Logging

Migrations uses the console by default for logging if not provided. If you want to use your own logger (for sending to other consumers or similar) you can do so by configuring the logger option when calling migrator.config.

Log levels conform to those in node.js Console API.

Winston example

import { createLogger } from 'winston';

const logger = createLogger({
  transports: [
    new winston.transports.Console();
  ]
});

const myLogger = (level, message) => {
  logger.log({
    level,
    message
  });
}

migrator.config({
  ...
  logger: myLogger
  ...
});

Development

Run docker-compose to execute lib in dev mode

$ npm run docker:dev

Test

Run docker-compose to execute lib in test mode

$ npm run docker:test

Credits

Migration builds on percolatestudio/meteor-migrations with the goal of creating a generic mongodb migration library