Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Populate versions when adding {versions: true} to an existing collection

default discord avatar
r0bsoniklast year

I'll answer to my own issue here for others looking for it in future 😉



After adding

{versions: true}

the admin panel for the collection is broken, since it tries to retrieve drafts of the documents.



AI-bot directs to non existing section of the documentation (

https://payloadcms.com/docs/versions/overview#versions-may-need-to-be-migrated

)



The solution I managed to do is to use the new migration feature and create required versions.



QUESTION TO THE PAYLOAD TEAM:


Should this be part of documentation and is my solution correct/optimal? If so, let me know where do you see it will fit and I can add it 😉




My solution



Run


npm run migrate:create add-versions-to-posts

And add content to the file


export async function up({ payload }: MigrateUpArgs): Promise<void> {
  const {docs} = await payload.find({ collection: 'posts' })
  for (const post of docs) {
    const VersionsModel = payload.db.versions['posts']
    await VersionsModel.create({
      parent: post.id,
      version: post,
      createdAt: post.createdAt ?? Date.now(),
      updatedAt: post.updatedAt ?? Date.now(),
      autosave: false,
      __v: 0,
      latest: true,
    })
  }
}

export async function down({ payload }: MigrateDownArgs): Promise<void> {
  const VersionsModel = payload.db.versions['posts']
  await VersionsModel.deleteMany({})
}
    Star on GitHub

    Star

    Chat on Discord

    Discord

    online

    Can't find what you're looking for?

    Get dedicated engineering support directly from the Payload team.