How do I migrate docs after a schema change?

discord user avatar
jacobsfletch
Payload Team
last year
6 1
  • How do I resave all posts programmatically?
  • How do I migrate docs after a schema change?

These are common questions and fortunately pretty easy to solve using a migration script. All we have to do is spin up Payload, find all records within a given collection, and then immediately update each. If needed, we can also modify the data before it gets updated:

const payload = require('payload');

require('dotenv').config();

payload.init({
  secret: process.env.PAYLOAD_SECRET,
  mongoURL: process.env.MONGO_URL,
  local: true,
});

const resaveCollection = async () => {
  const args = process.argv.slice(2); // nodejs command line args are an array that begin at the third item
  const [
    collectionSlug,
    overrides
  ] = args || [];

  const results = await payload.find({
    collection: collectionSlug,
    depth: 0,
    limit: 700,
  });

  try {
    await Promise.all(results.docs.map(async (result) => {
      const { id } = result;

      if (collectionSlug) {
        try {
          await payload.update({
            collection: collectionSlug,
            id,
            data: {
              ...overrides || {}
            },
          })

          console.log(`Document in '${collectionSlug}' with id '${id}' updated successfully`);
        } catch (e) {
          payload.logger.error(`Document in '${collectionSlug}' with id '${id}' failed to update`);
          payload.logger.error(e);
        }
      } else {
        console.log(`No document found in '${collectionSlug}' with id '${id}'`);
      }
    }));
  } catch (e) {
    payload.logger.error('Something went wrong.');
    payload.logger.error(e);
  }

  console.log('Complete');
  process.exit(0);
};

resaveCollection();

To run it, send the slug of the collection along with optional overrides for node to execute:

node scripts/resaveCollection pages

^ Your specific file path may different. Update this based on your specifications. Also note that Payload may need to know the location of your config, see this page for more detail.

  • discord user avatar
    jacobsfletch
    Payload Team
    8 months ago

    If you're here needing to regenerate media after changing image sizes, check out this discussion: #1834

Open the post
Continue the discussion in GitHub
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.