{"id":16799,"library":"database-updates","title":"Database Schema Updater","description":"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.","status":"active","version":"4.1.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/domharrington/database-updates","tags":["javascript","typescript"],"install":[{"cmd":"npm install database-updates","lang":"bash","label":"npm"},{"cmd":"yarn add database-updates","lang":"bash","label":"yarn"},{"cmd":"pnpm add database-updates","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For ESM environments, use the default import. The main export is a function that can be called directly.","wrong":"const databaseUpdates = require('database-updates').default","symbol":"databaseUpdates","correct":"import databaseUpdates from 'database-updates'"},{"note":"The primary package export is a function, commonly used directly after a CommonJS require.","symbol":"databaseUpdates (CommonJS)","correct":"const databaseUpdates = require('database-updates')"},{"note":"While the quickstart uses the direct function call, the `DatabaseUpdates` class can be instantiated for more control or dependency injection. For CommonJS, use `const { DatabaseUpdates } = require('database-updates');`.","wrong":"const { DatabaseUpdates } = require('database-updates').default","symbol":"DatabaseUpdates (class constructor)","correct":"import { DatabaseUpdates } from 'database-updates'"}],"quickstart":{"code":"const { MongoClient } = require('mongodb')\nconst databaseUpdates = require('database-updates')\n\nasync function main() {\n  const client = await MongoClient.connect(\n    'mongodb://localhost/database-updates-example',\n    { useNewUrlParser: true, useUnifiedTopology: true } // Add options for modern MongoClient\n  )\n\n  // Optional: Drop the database for a clean run in development\n  await client.db().dropDatabase()\n\n  // Define a simple update script path for demonstration\n  const updateScriptPath = `${__dirname}/temp_updates`\n  require('fs').mkdirSync(updateScriptPath, { recursive: true })\n  require('fs').writeFileSync(\n    `${updateScriptPath}/0.0.1-initial-collection.js`,\n    `module.exports = async (db) => {\n      await db.createCollection('users')\n      console.log('Created users collection.')\n    }`\n  )\n\n  console.log('Applying database updates...')\n  await databaseUpdates({\n    db: client.db(),\n    updatePath: updateScriptPath,\n    logger: console\n  }).run()\n\n  console.log('Done! Check your MongoDB instance for the \"users\" collection.')\n  return client.close()\n}\n\nmain().catch((e) => {\n  console.error('An error occurred:', e)\n  process.exit(1)\n})","lang":"javascript","description":"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."},"warnings":[{"fix":"Ensure your Node.js runtime environment is configured to handle dynamic TypeScript imports for `.ts` update files. This often involves using a tool like `ts-node/register` or transpiling `.ts` files to `.js` before execution, or configuring Node.js to recognize `.ts` files as modules.","message":"TypeScript support is explicitly experimental. It relies on your runtime's ability to dynamically `import()` `.ts` files, which typically requires a specific setup (e.g., using `ts-node` or a custom module loader) and may not work out-of-the-box in standard Node.js environments.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Verify all update script filenames conform to the `major.minor.patch-description.ext` format. The version part dictates the execution order.","message":"Update script filenames MUST adhere strictly to Semantic Versioning (SemVer) followed by a dash and description (e.g., `X.Y.Z-description.js`). Incorrect naming will result in scripts not being run or executed in an unexpected order.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"For CommonJS, use `module.exports = function (db) { ... }`. For ES Modules, use `export default function (db) { ... }` or `export default (db) => { ... }`. Ensure the function signature is `(db) => { ... }`.","message":"Each update script must export a function that accepts the database connection as its first and only argument. This function can be synchronous, asynchronous, or return a Promise. Incorrect export signatures will prevent the script from running.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For new changes, create a new update script with an incremented SemVer filename. To force a re-run of an existing script in a development environment, manually delete its entry from the `databaseUpdates` collection in your database.","message":"An update script, once successfully run, will never be executed again on the same machine/environment. The applied updates are recorded in a configurable collection (default `databaseUpdates`). If an update needs to be re-run, a new versioned script must be created, or the entry manually removed from the `databaseUpdates` collection.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"If using `.ts` files, ensure `ts-node` is installed and registered (e.g., `node -r ts-node/register your-app.js`) or transpile your `.ts` files to `.js` before running. For ESM `.ts` files, ensure your project is configured for ESM (e.g., `\"type\": \"module\"` in `package.json`) and you're using dynamic `import()` where necessary.","cause":"Attempting to use a `.ts` update script without configuring the Node.js runtime to handle TypeScript files, or trying to `require()` an ESM-style `.ts` file in a CJS context.","error":"Error: Cannot find module 'path/to/my-update.ts' or SyntaxError: Cannot use import statement outside a module"},{"fix":"Review the update script file to ensure it exports a function with the `(db)` signature correctly. Check for typos in `module.exports` or `export default`.","cause":"The update script file does not have the expected function export (`module.exports = function(db){}` or `export default function(db){}`).","error":"Error: Update script 'path/to/0.0.1-my-update.js' did not export a function"},{"fix":"Ensure your database connection is directed to the primary replica set member for write operations, or configure appropriate write concerns and read preferences for your `MongoClient` instance if you intend to write to secondaries (which is generally not recommended for migrations).","cause":"This error occurs when attempting to perform write operations (like creating collections or indexes) on a MongoDB replica set secondary member without appropriate write concerns or read preferences.","error":"MongoError: not master and slaveOk=false"}],"ecosystem":"npm","meta_description":null}