{"id":16642,"library":"masterrecord","title":"MasterRecord ORM","description":"MasterRecord is a lightweight, code-first Object-Relational Mapper (ORM) for Node.js, currently at version 1.0.4. It emphasizes a fluent, lambda-based query API, a comprehensive CLI-driven migration system, and out-of-the-box support for multiple relational databases including MySQL (5.7+/8.0+), PostgreSQL (9.6+/12+), and SQLite (3.x). The ORM operates on an Active Record pattern, providing entity serialization, lifecycle hooks, and built-in validation. A key differentiator is its \"ESM only\" nature, requiring Node.js 20+ and a host project configured as a module, with no CommonJS build available. It offers features like query result caching, bulk operations, and robust SQL injection protection through parameterized queries. The project seems to follow a stable release cadence with its initial major v1.0 release.","status":"active","version":"1.0.4","language":"javascript","source_language":"en","source_url":"https://github.com/Tailor/Masterrecord","tags":["javascript","orm","database","migrations","mysql","sqlite","postgres","esm","masterrecord"],"install":[{"cmd":"npm install masterrecord","lang":"bash","label":"npm"},{"cmd":"yarn add masterrecord","lang":"bash","label":"yarn"},{"cmd":"pnpm add masterrecord","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"MasterRecord is a pure ESM package since v1.0, requiring Node.js 20+ and '\"type\": \"module\"' in package.json. This import typically accesses the global configuration and factory methods.","wrong":"const { MasterRecord } = require('masterrecord');","symbol":"MasterRecord","correct":"import { MasterRecord } from 'masterrecord';"},{"note":"Used for programmatically defining new database entities and their schema. Follows ESM import syntax.","wrong":"const { defineEntity } = require('masterrecord');","symbol":"defineEntity","correct":"import { defineEntity } from 'masterrecord';"},{"note":"The base class for all data models. Custom entities should extend this class to gain ORM capabilities.","wrong":"const { Entity } = require('masterrecord');","symbol":"Entity","correct":"import { Entity } from 'masterrecord';"}],"quickstart":{"code":"import { MasterRecord } from 'masterrecord';\n\n// 1. Define an entity extending MasterRecord.Entity\nclass User extends MasterRecord.Entity {\n  id!: number;\n  name!: string;\n  email!: string;\n  age?: number;\n\n  static tableName = 'users'; // Explicitly define the table name\n\n  static fields = {\n    id: { type: 'number', primaryKey: true, autoIncrement: true },\n    name: { type: 'string', required: true, length: { min: 3, max: 255 } },\n    email: { type: 'string', required: true, pattern: /^\\S+@\\S+\\.\\S+$/, unique: true },\n    age: { type: 'number', required: false, min: 18 }\n  };\n}\n\nasync function runMasterRecord() {\n  // 2. Configure MasterRecord for SQLite database\n  await MasterRecord.configure({\n    connection: {\n      client: 'sqlite',\n      filename: './quickstart.sqlite'\n    },\n    entities: [User],\n    debug: process.env.NODE_ENV !== 'production' // Enable logging in development\n  });\n\n  // 3. Sync schema (for development; use migrations in production)\n  await MasterRecord.syncSchema();\n  console.log('Database schema synced successfully for User entity.');\n\n  // 4. Create a new user instance using the factory method\n  const newUser = MasterRecord.create(User, { \n    name: 'Alice Wonderland',\n    email: 'alice@example.com',\n    age: 28 \n  });\n  await newUser.save();\n  console.log('Created new user:', newUser.toObject());\n\n  // 5. Find a user by email\n  const foundUser = await MasterRecord.query(User).where(u => u.email === 'alice@example.com').first();\n  if (foundUser) {\n    console.log('Found user:', foundUser.toObject());\n    // 6. Update the user\n    foundUser.age = 29;\n    await foundUser.save();\n    console.log('Updated user age:', foundUser.toObject());\n  }\n\n  // 7. Disconnect from the database\n  await MasterRecord.disconnect();\n  console.log('MasterRecord disconnected.');\n}\n\nrunMasterRecord().catch(console.error);\n","lang":"typescript","description":"This quickstart demonstrates how to configure MasterRecord with an SQLite database, define a `User` entity, sync the schema, and perform basic CRUD operations (create, save, query) on entity instances."},"warnings":[{"fix":"Ensure Node.js >=20.0.0 is installed and your project's `package.json` has `\"type\": \"module\"`. Update import statements to use ESM syntax (e.g., `import { MasterRecord } from 'masterrecord';`).","message":"MasterRecord v1.0+ is a pure ECMAScript Module (ESM) package. It does not provide a CommonJS build and requires Node.js v20.0.0 or higher. Your project's `package.json` must include `\"type\": \"module\"`.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Always use `const newEntity = MasterRecord.create(YourEntityClass, { ...data });` to ensure full ORM functionality and adherence to defined business logic and lifecycle processes.","message":"When creating new entity instances, it is critical to use the `MasterRecord.create(Entity, data)` factory method instead of directly instantiating with `new Entity(data)`. Direct instantiation bypasses internal lifecycle hooks, validation, and proper field initialization.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Prioritize using MasterRecord's fluent query builder for all data operations. If raw SQL is absolutely necessary, rigorously validate and sanitize all user-supplied input and utilize parameterized queries diligently.","message":"While MasterRecord offers 'Raw SQL Queries' as an advanced feature, developers should exercise extreme caution. Although the ORM's primary query API provides automatic SQL injection protection, direct raw SQL requires manual parameterization and sanitization to prevent security vulnerabilities.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For production deployments, utilize the MasterRecord CLI to generate and run migrations (`masterrecord migrate up`, `masterrecord migrate down`) to manage schema changes in a controlled and versioned manner.","message":"The `MasterRecord.syncSchema()` method is convenient for rapid development and testing but should not be used in production environments, as it can lead to data loss or unintended schema changes. Production environments should rely exclusively on the CLI-driven migration system.","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":"Ensure your project's `package.json` has `\"type\": \"module\"` and use `import { ... } from 'masterrecord';` syntax. Upgrade your Node.js environment to version 20.0.0 or newer.","cause":"Attempting to import MasterRecord using CommonJS `require()` syntax in a non-ESM project, or in an older Node.js environment.","error":"ERR_REQUIRE_ESM: require() of ES module .../masterrecord/index.js from ... not supported."},{"fix":"Upgrade your Node.js environment to version 20.0.0 or newer. Consider using a version manager like `nvm` or `volta` to manage Node.js versions.","cause":"Running MasterRecord with an incompatible Node.js version.","error":"Error: The current Node.js version (vX.Y.Z) is not supported. MasterRecord requires Node.js v20.0.0 or higher."},{"fix":"Always ensure you are correctly importing `MasterRecord` and using the factory method as `const newEntity = MasterRecord.create(YourEntityClass, { data });`.","cause":"Attempting to create an entity instance directly via `new YourEntityClass()` instead of using the factory method, or incorrectly accessing the `create` method.","error":"TypeError: MasterRecord.create is not a function OR Cannot read properties of undefined (reading 'create')"},{"fix":"Verify that your database server is running and accessible. Double-check all connection parameters in your `MasterRecord.configure()` settings. Ensure no firewalls are blocking the connection. For SQLite, check the `filename` path and file system permissions.","cause":"The database server is not running, is inaccessible from the application's host, or the connection credentials (host, port, user, password, database) are incorrect. For SQLite, the path to the database file might be invalid or permissions might be insufficient.","error":"Error: connect ECONNREFUSED 127.0.0.1:3306 (for MySQL) / Connection refused (for PostgreSQL) / SQLITE_CANTOPEN: unable to open database file"}],"ecosystem":"npm"}