MongoDB Schema Migration Guide

Stack: MERN (MongoDB, Express, React, Node.js) Last Updated: April 2026


Why This Document Exists

As our user base grows, changing the MongoDB schema becomes risky. Adding a required: true field to a Mongoose model when existing documents don’t have that field will crash the app on deployment.

This guide defines the standard process every engineer must follow when making schema changes — so we never break production again.


The Core Problem

We need to add startDate and endDate to the Subscription model and mark both as required: true.

// ❌ What NOT to do — deploying this directly will crash the app
startDate: { type: Date, required: true },
endDate:   { type: Date, required: true }

Every existing subscription document in the database does not have these fields. The moment this code is deployed, Mongoose will throw a validation error on every existing subscription. The app goes down immediately.


The Solution: Migrate First, Deploy Second

Always update the data in the database BEFORE deploying the code that requires it.

This is done using a tool called migrate-mongo, which lets us write database update scripts in an organised, trackable, and reversible way.

Think of it like git — but for your database. It remembers which scripts have already run, so nothing gets applied twice.


One-Time Setup

Run this once in the project root.

1. Install migrate-mongo