Database Schema Updater

4.1.0 · active · verified Wed Apr 22

database-updates is a Node.js library designed to manage and apply database schema and data migration scripts in a versioned, reliable manner. It is currently at version 4.1.0 and appears to be actively maintained, though no explicit release cadence is stated beyond following semantic versioning for its own releases. The core differentiator is its reliance on SemVer (Semantic Versioning) compliant filenames for update scripts (e.g., `1.0.0-initial-setup.js`), which dictates the execution order and ensures each script runs exactly once per environment. This mechanism prevents inconsistencies across development, staging, and production environments. It supports both CommonJS and ES Module update scripts and offers experimental support for TypeScript update files, provided the runtime can dynamically `import()` them. It's particularly useful for applications built on MongoDB or similar NoSQL databases where schema changes are often handled via code-based migrations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `database-updates` with a MongoDB connection, define an update script, and execute the updates. It creates a temporary update file and ensures the database is updated according to the semver filename.

const { MongoClient } = require('mongodb')
const databaseUpdates = require('database-updates')

async function main() {
  const client = await MongoClient.connect(
    'mongodb://localhost/database-updates-example',
    { useNewUrlParser: true, useUnifiedTopology: true } // Add options for modern MongoClient
  )

  // Optional: Drop the database for a clean run in development
  await client.db().dropDatabase()

  // Define a simple update script path for demonstration
  const updateScriptPath = `${__dirname}/temp_updates`
  require('fs').mkdirSync(updateScriptPath, { recursive: true })
  require('fs').writeFileSync(
    `${updateScriptPath}/0.0.1-initial-collection.js`,
    `module.exports = async (db) => {
      await db.createCollection('users')
      console.log('Created users collection.')
    }`
  )

  console.log('Applying database updates...')
  await databaseUpdates({
    db: client.db(),
    updatePath: updateScriptPath,
    logger: console
  }).run()

  console.log('Done! Check your MongoDB instance for the "users" collection.')
  return client.close()
}

main().catch((e) => {
  console.error('An error occurred:', e)
  process.exit(1)
})

view raw JSON →