{"id":16654,"library":"nc-db-new","title":"NextUp Comedy Database Models","description":"The `nc-db-new` package provides the foundational database models for the NextUp Comedy website and its associated services. Designed as an internal library, it centralizes the schema definitions, relationships, and often the data access logic for core entities such as Users, Shows, Venues, and Bookings specific to the comedy platform. Currently at version 1.6.7, this package ensures consistent data structures across various backend applications and microservices within the NextUp Comedy ecosystem. Its primary function is to abstract database interactions, enabling developers to work with TypeScript classes or interfaces that map directly to database tables. While its release cadence is tied to internal development cycles, it aims for stability in its minor and patch versions, with breaking changes typically confined to major version bumps. Key differentiators are its highly specialized domain model and its deep integration into the NextUp Comedy tech stack, providing a single source of truth for database schema.","status":"active","version":"1.6.7","language":"javascript","source_language":"en","source_url":"https://github.com/NextUp-comedy/db-models-nc","tags":["javascript","NextUp Comedy","models","database","typescript"],"install":[{"cmd":"npm install nc-db-new","lang":"bash","label":"npm"},{"cmd":"yarn add nc-db-new","lang":"bash","label":"yarn"},{"cmd":"pnpm add nc-db-new","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Prefer ES module imports; CommonJS `require` might not work correctly or lead to type issues, especially in newer Node.js environments.","wrong":"const { User } = require('nc-db-new');","symbol":"User","correct":"import { User } from 'nc-db-new';"},{"note":"Individual models are typically exported as named exports. Avoid default imports unless explicitly specified by the library.","symbol":"Show","correct":"import { Show } from 'nc-db-new';"},{"note":"When importing only types, use `import type` to ensure they are stripped from the JavaScript output, preventing potential runtime errors or unnecessary bundle size increase.","wrong":"import { UserAttributes } from 'nc-db-new';","symbol":"UserAttributes","correct":"import type { UserAttributes } from 'nc-db-new';"}],"quickstart":{"code":"import { User, Show, db } from 'nc-db-new';\n\nasync function main() {\n  // Assume 'db' is an initialized ORM instance or connection pool\n  // For demonstration, we'll mock 'db.sync' and 'User.create'\n  console.log('Synchronizing database models...');\n  // await db.sync(); // In a real app, this might create/update tables\n  console.log('Database models synchronized.');\n\n  try {\n    const newUser = await User.create({\n      username: 'comedyfan',\n      email: `fan_${Date.now()}@example.com`,\n      passwordHash: 'hashedpassword123',\n      is_admin: false\n    });\n    console.log('Created new user:', newUser.toJSON());\n\n    const allUsers = await User.findAll();\n    console.log('Total users:', allUsers.length);\n\n    const firstShow = await Show.findOne({\n      where: { title: 'The Laughter Gala' }\n    });\n\n    if (firstShow) {\n      console.log('Found show:', firstShow.toJSON());\n    } else {\n      console.log('No show found with title \"The Laughter Gala\", creating one...');\n      const createdShow = await Show.create({\n        title: 'The Laughter Gala',\n        date: new Date('2026-07-20T19:00:00Z'),\n        venueId: 'venue-abc-123' // Assume a venue ID exists or is created elsewhere\n      });\n      console.log('Created new show:', createdShow.toJSON());\n    }\n  } catch (error) {\n    console.error('Database operation failed:', error);\n  }\n}\n\n// Simulate an initialized 'db' object and model methods for the quickstart\nconst mockDb = {\n  sync: async () => Promise.resolve(),\n};\nconst mockUser = {\n  create: async (data: any) => ({ ...data, id: Math.random().toString(36).substring(7), toJSON: () => ({ ...data, id: 'mock-user-id' }) }),\n  findAll: async () => ([{ username: 'existing', email: 'existing@example.com', toJSON: () => ({ username: 'existing', email: 'existing@example.com' }) }]),\n  toJSON: () => ({}) // For compatibility\n};\nconst mockShow = {\n  findOne: async (options: any) => options.where.title === 'The Laughter Gala' ? null : ({ title: 'Existing Comedy Night', date: new Date(), toJSON: () => ({ title: 'Existing Comedy Night' }) }),\n  create: async (data: any) => ({ ...data, id: Math.random().toString(36).substring(7), toJSON: () => ({ ...data, id: 'mock-show-id' }) })\n};\n\n// Overwrite for quickstart execution\n// @ts-ignore\n(globalThis as any).db = mockDb;\n// @ts-ignore\n(globalThis as any).User = mockUser;\n// @ts-ignore\n(globalThis as any).Show = mockShow;\n\nmain();","lang":"typescript","description":"Demonstrates importing `User` and `Show` models, simulating database operations like creating and finding entities."},"warnings":[{"fix":"Implement robust migration strategies using tools like Flyway, Liquibase, or ORM-specific migration utilities. Validate schema synchronization in CI/CD pipelines.","message":"Schema drift can occur if database migrations are not run consistently with model changes. Always ensure your database schema matches the model definitions in the `nc-db-new` package.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review the package's changelog thoroughly for breaking changes. Update your application code, database migrations, and data transformation scripts as necessary to align with the new version.","message":"Major version updates (e.g., from v1 to v2) are likely to introduce breaking changes in model definitions, field types, or relationships. Always consult the changelog before upgrading.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Ensure the database connection and ORM (if applicable) are correctly initialized and passed to the models, or globally accessible, before attempting any database interactions. Verify connection string, credentials, and pool settings.","message":"The models typically rely on an underlying ORM or database connection instance (e.g., `db`). Incorrect initialization or configuration of this instance will lead to runtime errors when performing database operations.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Utilize ORM features like `include` or `join` to eager load related data. Analyze query performance using database monitoring tools and refactor data access patterns to reduce redundant queries.","message":"Performance issues like N+1 queries can arise from inefficient data fetching patterns, especially when dealing with related entities. Eager loading or careful query construction is often required.","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 `db` and models are correctly imported and initialized. Verify that the database connection is established and the ORM instance is available where models are being used.","cause":"The `db` object or specific model (e.g., `User`) was not properly initialized or imported before use, or the underlying ORM instance is not connected.","error":"TypeError: Cannot read properties of undefined (reading 'create')"},{"fix":"Update your model definitions in `nc-db-new` if `someField` is new. If it's an existing field, ensure your query explicitly selects it, or that the return type of your query includes it.","cause":"Attempting to access a field that is not defined in the `User` model's TypeScript interface or class, or a field that was not explicitly selected in a query.","error":"Property 'someField' does not exist on type 'User'."},{"fix":"Review your model's create/update data to ensure all required fields (especially `NOT NULL` columns) are provided with valid values.","cause":"Attempted to insert or update a database record without providing a value for a column that is marked as `NOT NULL` in the database schema.","error":"Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: users.email"}],"ecosystem":"npm"}