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

mongo-migrate-ts

v1.4.0

Published

[![CircleCI](https://circleci.com/gh/mycodeself/mongo-migrate-ts.svg?style=svg)](https://circleci.com/gh/mycodeself/mongo-migrate-ts)

Downloads

43,790

Readme

mongo-migrate-ts

CircleCI

A library for easy run migrations on mongodb with TypeScript.

Based on migrate-mongo (https://github.com/seppevs/migrate-mongo/), but with TypeScript support.

Installation

Install using your favourite package manager, example using npm

npm install mongo-migrate-ts

You can install it globally for the CLI usage

npm install -g mongo-migrate-ts

Usage

CLI options

Usage: mongo-migrate [options] [command]

Options:
  -h, --help      output usage information

Commands:
  init            Creates the migrations directory and configuration file
  new [options]   Create a new migration file under migrations directory
  up              Run all pending migrations
  down [options]  Undo migrations
  status          Show the status of the migrations

Create a directory for your migrations and instantiate a CLI

import { mongoMigrateCli } from 'mongo-migrate-ts';

mongoMigrateCli({
  uri: 'mongodb://username:[email protected]:27017',
  database: 'db',
  migrationsDir: __dirname,
  migrationsCollection: 'migrations_collection',
});

Create a migration file in the configured migrations folder...

import { MigrationInterface } from 'mongo-migrate-ts';
import { Db } from 'mongodb';

export class MyMigration implements MigrationInterface {
  async up(db: Db): Promise<any> {
    await db.createCollection('my_collection');
  }

  async down(db: Db): Promise<any> {
    await db.dropCollection('my_collection');
  }
}

Compile and up all migrations

tsc migrations/index.js && node build/migrations/index.js up

or run directly with ts-node

ts-node migrations/index.ts up

Configuration

{
  // The path where the migrations are stored
  migrationsDir: string;
  // The name of the collection to store the applied migrations
  // (Default: "migrations_changelog")
  migrationsCollection?: string;
  // The connection uri, it can be empty if useEnv is true
  // (Example: mongodb://user:[email protected]:27017/db?authSource=admin)
  uri?: string;
  // The database where run the migrations
  // it can be empty if the database is on the uri or useEnv is true
  database?: string;
  // If true, will load the configuration from environment variables.
  useEnv?: boolean;
  // Options related to environment configuration
  environment?: {
    // The name of the environment variable with the uri connection
    // (Default: MONGO_MIGRATE_URI)
    uriVar?: string;
    // The name of the environment variable with the db name
    // (Default: MONGO_MIGRATE_DB)
    databaseVar?: string;
  };
  // Specific configuration of mongodb client
  // (see https://mongodb.github.io/node-mongodb-native/4.3/interfaces/MongoClientOptions.html)
  options?: MongoClientOptions;
}

Example configuration in json

{
  "uri": "mongodb://admin:[email protected]:27017/mydb?authSource=admin",
  "migrationsDir": "migrations"
}

Transactions

The up and down methods in migrations have the mongo client available to create a session and use transactions. See example

import { Db, MongoClient } from 'mongodb';
import { MigrationInterface } from '../../lib';

export class Transaction1691171075957 implements MigrationInterface {
  public async up(db: Db, client: MongoClient): Promise<any> {
    const session = client.startSession();
    try {
      await session.withTransaction(async () => {
        await db.collection('mycol').insertOne({ foo: 'one' });
        await db.collection('mycol').insertOne({ foo: 'two' });
        await db.collection('mycol').insertOne({ foo: 'three' });
      });
    } finally {
      await session.endSession();
    }
  }

  public async down(db: Db, client: MongoClient): Promise<any> {
    const session = client.startSession();
    try {
      await session.withTransaction(async () => {
        await db.collection('mycol').deleteOne({ foo: 'one' });
        await db.collection('mycol').deleteOne({ foo: 'two' });
        await db.collection('mycol').deleteOne({ foo: 'three' });
      });
    } finally {
      await session.endSession();
    }
  }
}