This repo is a working demonstration of using mongo-migrate
in a Payload CMS project
- App is developed
- Tested
- Goes to production
- Actual data is created over time
- App needs to have data changed on fields and collections with existing data
This is a demonstration of what to do at this step.
npx create-payload-app
cd
to newly created projectyarn add migrate-mongo
yarn migrate-mongo init
- Customize your migrate-mongo-config.js to have the connection string of your mongo database
- Add script to package.json to make using migrations easier
"migrate": "migrate-mongo"
See example changes in Users.ts, changes to name fields left in comments. See migration 20221221120758-update-users-change-name.js
- Make changes to existing Payload collections
- If a migration to change existing data is necessary:
yarn migrate create update_collection-name_rename_field
, come up with a consistent format & naming convention for migration files- Write the
up
anddown
functions to perform the changes needed, test using local data with simulated production data - Commit both the migrations and code changes together in a branch and merge it
- When pulling changes to a new environment (dev, staging, prod) with data, run
yarn migrate up
andyarn migrate status
to verify
Migrations are only needed when existing data has changed, they are not needed for simply adding a new field or index. Another use-case for migrations is to insert necessary data for applications to function. Suppose you are adding roles
as a relationship to be defined on User collections which you want stored in the database and consistent across environments, this is one example and there are many more.