migrate-mongo-example
migrate-mongo-example copied to clipboard
Payload project using migrate-mongo to demonstrate migrations
Migrate Mongo Payload Example
This repo is a working demonstration of using mongo-migrate in a Payload CMS project
In a real world scenario
- 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.
Recreating this setup
npx create-payload-appcdto newly created projectyarn add migrate-mongoyarn 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
Workflow for development
- 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
upanddownfunctions 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 upandyarn migrate statusto 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.