Bird
0
0

You want to add a new required field age Int to your User model in Prisma. However, your database already has existing users without this field. What is the best way to handle this migration safely?

hard📝 Application Q15 of 15
NestJS - Database with Prisma
You want to add a new required field age Int to your User model in Prisma. However, your database already has existing users without this field. What is the best way to handle this migration safely?
ADelete all existing users before running migration
BAdd the field as optional first, run a migration, then update data and make it required in a second migration
CAdd the required field directly and run migrate dev once
DSkip migrations and manually update the database schema
Step-by-Step Solution
Solution:
  1. Step 1: Understand required field impact

    Adding a required field means existing rows must have a value, or migration will fail.
  2. Step 2: Apply a two-step migration strategy

    First add the field as optional, migrate, update existing data with values, then change field to required and migrate again.
  3. Final Answer:

    Add the field as optional first, run a migration, then update data and make it required in a second migration -> Option B
  4. Quick Check:

    Two-step migration avoids missing data errors [OK]
Quick Trick: Add required fields in two steps to avoid errors [OK]
Common Mistakes:
  • Adding required fields directly causing migration failure
  • Deleting data unnecessarily
  • Skipping migrations and editing DB manually

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes