Like what we’re doing? Star us on GitHub!

How to resave all posts programmatically (migrate data)

Payload Team
last year
5 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');


  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 [
  ] = args || [];

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

  try {
    await Promise.all( (result) => {
      const { id } = result;

      if (collectionSlug) {
        try {
          await payload.update({
            collection: collectionSlug,
            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`);
      } else {
        console.log(`No document found in '${collectionSlug}' with id '${id}'`);
  } catch (e) {
    payload.logger.error('Something went wrong.');



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.

  • jacobsfletch
    Payload Team
    2 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
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More