schema-upgrade
Database-agnostic schema upgrading library.
Usage
{ const Schema = // connect to mongodb const MongoClient = const mongoClient = await 'mongodb://localhost:27017' const db = await mongoClient // get current schema version const collection = db let appInfo = await collection // appInfo doesn't exist, this is the first time we run the app // initialize appInfo struct if !appInfo appInfo = key: 'appInfo' version: 0 // set initial version to 0 upgrading: false await collection await collection // create a schema object, provide current db's schema version const schema = appInfoversion db // version 1 schemaversion1 async { console await db console } // version 2 schemaversion2 async { console await db console } // get the latest version const latest = schema // if db's schema version is the latest // no upgrade is needed if latest === appInfoversion return // else we upgrade the schema // set 'upgrading' to true to lock the db const result = await collection // if 'upgrading' is already true // the other server is performing the upgrading if !resultmodifiedCount throw 'Other process is upgrading the database. Please wait.' // upgrade console await schema // unlock db await collection // finished}
APIs
new Schema(currentVersion, ...args)
Create a schema object.
currentVersion
Number
. Current schema version.
...args
Any
. The arguments passed to upgradeFunction
.
schema.version(versionNumber, upgradeFunction)
Defines a version.
versionNumber
Number
. The version number.
upgradeFunction(...args)
Function
. The upgrade function. It should return a Promise
.
schema.latest()
Returns the latest version number, or null
if no version is defined.
schema.upgrade()
Run the upgrade operations.
It will run the upgradeFunction
from the next version to the latest version.
Returns: Promise
. Resolves to true
when upgrade is completed. Rejects if any error occurred.
LICENSE
MIT