Gathering detailed insights and metrics for migrate-mongo-ssh-tunnel
Gathering detailed insights and metrics for migrate-mongo-ssh-tunnel
Gathering detailed insights and metrics for migrate-mongo-ssh-tunnel
Gathering detailed insights and metrics for migrate-mongo-ssh-tunnel
npm install migrate-mongo-ssh-tunnel
Typescript
Module System
Min. Node Version
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1$ npm install -g migrate-mongo
$ migrate-mongo
Usage: migrate-mongo [options] [command]
Commands:
init initialize a new migration project
create [description] create a new database migration with the provided description
up [options] run all unapplied database migrations
down [options] undo the last applied database migration
status [options] print the changelog of the database
Options:
-h, --help output usage information
-V, --version output the version number
Make sure you have Node.js 10 (or higher) installed.
Create a directory where you want to store your migrations for your mongo database (eg. 'albums' here) and cd into it
1$ mkdir albums-migrations 2$ cd albums-migrations
Initialize a new migrate-mongo project
1$ migrate-mongo init 2Initialization successful. Please edit the generated migrate-mongo-config.js file
The above command did two things:
Edit the migrate-mongo-config.js file. An object or promise can be returned. Make sure you change the mongodb url:
1// In this file you can configure migrate-mongo 2 3module.exports = { 4 mongodb: { 5 // TODO Change (or review) the url to your MongoDB: 6 url: "mongodb://localhost:27017", 7 8 // TODO Change this to your database name: 9 databaseName: "YOURDATABASENAME", 10 11 options: { 12 useNewUrlParser: true, // removes a deprecation warning when connecting 13 // connectTimeoutMS: 3600000, // increase connection timeout to 1 hour 14 // socketTimeoutMS: 3600000, // increase socket timeout to 1 hour 15 }, 16 }, 17 18 // The migrations dir, can be an relative or absolute path. Only edit this when really necessary. 19 migrationsDir: "migrations", 20 21 // The mongodb collection where the applied changes are stored. Only edit this when really necessary. 22 changelogCollectionName: "changelog", 23 24 // The file extension to create migrations and search for in migration dir 25 migrationFileExtension: ".js", 26};
Alternatively, you can also encode your database name in the url (and leave out the databaseName
property):
url: "mongodb://localhost:27017/YOURDATABASE",
To create a new database migration script, just run the migrate-mongo create [description]
command.
For example:
1$ migrate-mongo create blacklist_the_beatles 2Created: migrations/20160608155948-blacklist_the_beatles.js
A new migration file is created in the 'migrations' directory:
1module.exports = { 2 up(db, client) { 3 // TODO write your migration here. Return a Promise (and/or use async & await). 4 // See https://github.com/seppevs/migrate-mongo/#creating-a-new-migration-script 5 // Example: 6 // return db.collection('albums').updateOne({artist: 'The Beatles'}, {$set: {blacklisted: true}}); 7 }, 8 9 down(db, client) { 10 // TODO write the statements to rollback your migration (if possible) 11 // Example: 12 // return db.collection('albums').updateOne({artist: 'The Beatles'}, {$set: {blacklisted: false}}); 13 }, 14};
Edit this content so it actually performs changes to your database. Don't forget to write the down part as well.
The db
object contains the official MongoDB db object
The client
object is a MongoClient instance (which you can omit if you don't use it).
There are 3 options to implement the up
and down
functions of your migration:
Always make sure the implementation matches the function signature:
function up(db, client) { /* */ }
should return Promise
function async up(db, client) { /* */ }
should contain await
keyword(s) and return Promise
function up(db, client, next) { /* */ }
should callback next
1module.exports = { 2 up(db) { 3 return db 4 .collection("albums") 5 .updateOne({ artist: "The Beatles" }, { $set: { blacklisted: true } }); 6 }, 7 8 down(db) { 9 return db 10 .collection("albums") 11 .updateOne({ artist: "The Beatles" }, { $set: { blacklisted: false } }); 12 }, 13};
Async & await is especially useful if you want to perform multiple operations against your MongoDB in one migration.
1module.exports = { 2 async up(db) { 3 await db 4 .collection("albums") 5 .updateOne({ artist: "The Beatles" }, { $set: { blacklisted: true } }); 6 await db 7 .collection("albums") 8 .updateOne({ artist: "The Doors" }, { $set: { stars: 5 } }); 9 }, 10 11 async down(db) { 12 await db 13 .collection("albums") 14 .updateOne({ artist: "The Doors" }, { $set: { stars: 0 } }); 15 await db 16 .collection("albums") 17 .updateOne({ artist: "The Beatles" }, { $set: { blacklisted: false } }); 18 }, 19};
Callbacks are supported for backwards compatibility. New migration scripts should be written using Promises and/or async & await. It's easier to read and write.
1module.exports = { 2 up(db, callback) { 3 return db 4 .collection("albums") 5 .updateOne( 6 { artist: "The Beatles" }, 7 { $set: { blacklisted: true } }, 8 callback 9 ); 10 }, 11 12 down(db, callback) { 13 return db 14 .collection("albums") 15 .updateOne( 16 { artist: "The Beatles" }, 17 { $set: { blacklisted: false } }, 18 callback 19 ); 20 }, 21};
To override the content of the sample migration that will be created by the create
command,
create a file sample-migration.js
in the migrations directory.
At any time, you can check which migrations are applied (or not)
1$ migrate-mongo status 2┌─────────────────────────────────────────┬────────────┐ 3│ Filename │ Applied At │ 4├─────────────────────────────────────────┼────────────┤ 5│ 20160608155948-blacklist_the_beatles.js │ PENDING │ 6└─────────────────────────────────────────┴────────────┘ 7
This command will apply all pending migrations
1$ migrate-mongo up 2MIGRATED UP: 20160608155948-blacklist_the_beatles.js
If an an error occurred, it will stop and won't continue with the rest of the pending migrations
If we check the status again, we can see the last migration was successfully applied:
1$ migrate-mongo status 2┌─────────────────────────────────────────┬──────────────────────────┐ 3│ Filename │ Applied At │ 4├─────────────────────────────────────────┼──────────────────────────┤ 5│ 20160608155948-blacklist_the_beatles.js │ 2016-06-08T20:13:30.415Z │ 6└─────────────────────────────────────────┴──────────────────────────┘
With this command, migrate-mongo will revert (only) the last applied migration
1$ migrate-mongo down 2MIGRATED DOWN: 20160608155948-blacklist_the_beatles.js
If we check the status again, we see that the reverted migration is pending again:
1$ migrate-mongo status 2┌─────────────────────────────────────────┬────────────┐ 3│ Filename │ Applied At │ 4├─────────────────────────────────────────┼────────────┤ 5│ 20160608155948-blacklist_the_beatles.js │ PENDING │ 6└─────────────────────────────────────────┴────────────┘
All actions (except init
) accept an optional -f
or --file
option to specify a path to a custom config file.
By default, migrate-mongo will look for a migrate-mongo-config.js
config file in of the current directory.
1$ migrate-mongo status -f '~/configs/albums-migrations.js' 2┌─────────────────────────────────────────┬────────────┐ 3│ Filename │ Applied At │ 4├─────────────────────────────────────────┼────────────┤ 5│ 20160608155948-blacklist_the_beatles.js │ PENDING │ 6└─────────────────────────────────────────┴────────────┘ 7
You can use use Node.js modules (or require other modules) in your migration scripts.
It's even possible to use npm modules, just provide a package.json
file in the root of your migration project:
1$ cd albums-migrations 2$ npm init --yes
Now you have a package.json file, and you can install your favorite npm modules that might help you in your migration scripts. For example, one of the very useful promise-fun npm modules.
You can make use of the MongoDB Transaction API in your migration scripts.
Note: this requires both:
migrate-mongo will call your migration up
and down
function with a second argument: client
.
This client
argument is an MongoClient instance, it gives you access to the startSession
function.
Example:
1module.exports = { 2 async up(db, client) { 3 const session = client.startSession(); 4 try { 5 await session.withTransaction(async () => { 6 await db 7 .collection("albums") 8 .updateOne( 9 { artist: "The Beatles" }, 10 { $set: { blacklisted: true } } 11 ); 12 await db 13 .collection("albums") 14 .updateOne({ artist: "The Doors" }, { $set: { stars: 5 } }); 15 }); 16 } finally { 17 await session.endSession(); 18 } 19 }, 20 21 async down(db, client) { 22 const session = client.startSession(); 23 try { 24 await session.withTransaction(async () => { 25 await db 26 .collection("albums") 27 .updateOne( 28 { artist: "The Beatles" }, 29 { $set: { blacklisted: false } } 30 ); 31 await db 32 .collection("albums") 33 .updateOne({ artist: "The Doors" }, { $set: { stars: 0 } }); 34 }); 35 } finally { 36 await session.endSession(); 37 } 38 }, 39};
To know which version of migrate-mongo you're running, just pass the version
option:
1$ migrate-mongo version
1const { 2 init, 3 create, 4 database, 5 config, 6 up, 7 down, 8 status, 9} = require("migrate-mongo");
init() → Promise
Initialize a new migrate-mongo project
1await init();
The above command did two things:
migrate-mongo-config.js
file andmigrations
directoryEdit the migrate-mongo-config.js
file. Make sure you change the mongodb url.
create(description) → Promise<fileName>
For example:
1const fileName = await create("blacklist_the_beatles"); 2console.log("Created:", fileName);
A new migration file is created in the migrations
directory.
database.connect() → Promise<{db: MongoDb, client: MongoClient}>
Connect to a mongo database using the connection settings from the migrate-mongo-config.js
file.
1const { db, client } = await database.connect();
config.read() → Promise<JSON>
Read connection settings from the migrate-mongo-config.js
file.
1const mongoConnectionSettings = await config.read();
config.set(yourConfigObject)
Tell migrate-mongo NOT to use the migrate-mongo-config.js
file, but instead use the config object passed as the first argument of this function.
When using this feature, please do this at the very beginning of your program.
Example:
1const { config, up } = require("../lib/migrate-mongo"); 2 3const myConfig = { 4 mongodb: { 5 url: "mongodb://localhost:27017/mydatabase", 6 options: { useNewUrlParser: true }, 7 }, 8 migrationsDir: "migrations", 9 changelogCollectionName: "changelog", 10 migrationFileExtension: ".js", 11}; 12 13config.set(myConfig); 14 15// then, use the API as you normally would, eg: 16await up();
up(MongoDb, MongoClient) → Promise<Array<fileName>>
Apply all pending migrations
1const { db, client } = await database.connect(); 2const migrated = await up(db, client); 3migrated.forEach((fileName) => console.log("Migrated:", fileName));
If an an error occurred, the promise will reject and won't continue with the rest of the pending migrations.
down(MongoDb, MongoClient) → Promise<Array<fileName>>
Revert (only) the last applied migration
1const { db, client } = await database.connect(); 2const migratedDown = await down(db, client); 3migratedDown.forEach((fileName) => console.log("Migrated Down:", fileName));
status(MongoDb) → Promise<Array<{ fileName, appliedAt }>>
Check which migrations are applied (or not.
1const { db } = await database.connect(); 2const migrationStatus = await status(db); 3migrationStatus.forEach(({ fileName, appliedAt }) => 4 console.log(fileName, ":", appliedAt) 5);
client.close() → Promise
Close the database connection
1const { db, client } = await database.connect(); 2await client.close();
No vulnerabilities found.
No security vulnerabilities found.