>  기사  >  웹 프론트엔드  >  Mongogrator - TS 및 JS용 MongoDB 마이그레이션 도구

Mongogrator - TS 및 JS용 MongoDB 마이그레이션 도구

Barbara Streisand
Barbara Streisand원래의
2024-10-02 06:40:30878검색

Mongogrator - a MongoDB migration tool for TS & JS

여기에 저장소

Mongogrator는 매우 빠른 MongoDB용 데이터베이스 마이그레이션 CLI입니다. 그 목적은 개발 및 프로덕션 단계에서 마이그레이션을 쉽게 생성하고 실행하는 것입니다

설치 중

다음 명령을 사용하면 Mongogrator가 자동으로 다운로드되어 설치되고 PATH에 추가됩니다

맥OS/리눅스

curl -fsSL git.new/mongogrator-installer.sh | bash

윈도우

powershell -c "irm git.new/mongogrator-installer.ps1 | iex"

명령 목록

Mongogrator CLI
Usage: mongogrator <command> [options]

Commands:
   init [--js]               Initialize a new configuration file
   add                       Creates a new migration file with the provided name
   list                      List all migrations and their status
   migrate [config_path]     Run all migrations that have not been applied yet
   version, -v, --version    Prints the current version of Mongogrator

Flags:
   --help, -h                Prints the detailed description of the command

이용안내

CLI 사용 기본 가이드

새 마이그레이션 추가

구성 파일 초기화로 시작

mongogrator init

명령어 위치에 mongogrator.config.ts 파일이 초기화됩니다. 선택적으로 명령 끝에 --js 플래그를 전달하여 js 파일에서 초기화할 수 있습니다

원하는 mongo 클러스터에 대한 URL을 설정하고 실행 중인지 확인하세요

mongogrator add insert_user

이렇게 하면 migrationsPath 구성에 할당된 디렉터리 키 아래에 마이그레이션 파일이 생성됩니다

다음은 새로 생성된 ts 마이그레이션 파일의 예시입니다

import type { Db } from 'mongodb'

/**
 * This function is called when the migration is run.
 * @param _db The mongodb database object that's passed to the migration
 */
export const migrate = async (_db: Db): Promise<void> => {
  // Migration code here
}

마이그레이션은 기본 MongoDB Node.js 드라이버를 통해 실행됩니다

마이그레이션 쿼리 예시

import type { Db } from 'mongodb'

/**
 * This function is called when the migration is run.
 * @param _db The mongodb database object that's passed to the migration
 */
export const migrate = async (_db: Db): Promise<void> => {
  // Migration code here
  _db.collection('users').insertOne({ name: 'Alex' })
}

마이그레이션 목록

원하는 만큼 마이그레이션을 추가한 다음 list 명령을 호출하여 각 마이그레이션의 상태를 표시할 수 있습니다

mongogrator list

이렇게 하면 모든 마이그레이션 목록이 인쇄되며 각 마이그레이션의 상태는 NOT MIGRATED 또는 MIGRATED

┌───┬───────────────────────────────┬──────────────┐
│   │ migration                     │ status       │
├───┼───────────────────────────────┼──────────────┤
│ 0 │ 20240923150201806_insert_user │ NOT MIGRATED │
└───┴───────────────────────────────┴──────────────┘

아직 마이그레이션을 실행하지 않았으므로 당연히 NOT MIGRATED 상태가 됩니다

마이그레이션 실행

전화만으로 마이그레이션을 실행하세요

mongogrator migrate

이렇게 하면 모든 마이그레이션이 실행되고 로그CollectionName 구성에 지정된 컬렉션 이름으로 데이터베이스에 기록됩니다.

프로덕션 목적으로 동일한 경로에서 액세스할 수 없는 경우 구성 경로를 마이그레이션 명령에 직접 전달할 수 있습니다

mongogrator migrate /dist

이제 다시 list 명령을 실행하면 마이그레이션 파일이 성공적으로 실행되었음을 알 수 있습니다

┌───┬───────────────────────────────┬──────────────┐
│   │ migration                     │ status       │
├───┼───────────────────────────────┼──────────────┤
│ 0 │ 20240923150201806_insert_user │ MIGRATED     │
└───┴───────────────────────────────┴──────────────┘

로그 수집 스키마

{
  _id: objectId(),
  name: string,
  createdAt: Date(),
}

구성

{
  url: 'mongodb://localhost:27017', // Cluster url
  database: 'test', // Database name for which the migrations will be executed
  migrationsPath: './migrations', // Migrations directory relative to the location of the commands
  logsCollectionName: 'migrations', // Name of the logs collection that will be stored in the database
  format: 'ts', // Format type of the migration files ['ts', 'js']
}

경로 값이 있는 모든 구성 키는 구성 파일 자체의 위치에 상대적입니다

위 내용은 Mongogrator - TS 및 JS용 MongoDB 마이그레이션 도구의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.