payload icon indicating copy to clipboard operation
payload copied to clipboard

docs: examples of common mongodb migrations

Open r1tsuu opened this issue 10 months ago • 4 comments

Adds some common mongodb migrations examples to the docs:

  • Delete field from the database
  • Synchronize indexes (which is the solution for common issues like this https://github.com/payloadcms/payload/issues/2007)
  • Making field localized and vice versa

r1tsuu avatar Jan 31 '25 03:01 r1tsuu

Maybe also make a note that this will not work with versioned collections?

andershermansen avatar Feb 05 '25 14:02 andershermansen

Maybe also make a note that this will not work with versioned collections?

You can make it work with versioned collections, you just would have to apply that migration for the versions collection. This can be noted

r1tsuu avatar Feb 05 '25 15:02 r1tsuu

Not necessarily related, but regarding the example for syncing indexes, should the migrateRelationshipsV2_V3 script include an option to sync all indexes?

I currently cannot run that script because I'm seeing an error that an index is missing. But the error does not list the culprit.

DallasO avatar Feb 05 '25 18:02 DallasO

@r1tsuu can you incorporate changing a collection name into this when you resolve the conflicts?

Example renaming a collection

The following example renames a collection with slug "pages" to "articles" and it includes migrating the _versions collection also.

import {
  MigrateDownArgs,
  MigrateUpArgs,
} from '@payloadcms/db-mongodb'
// import type { Db } from 'mongodb' // you will need to add this package as a devDependency in the package.json if you want db to be typed as Db

export async function up({ payload, req, session }: MigrateUpArgs): Promise<void> {
  const db = payload.db.connection.db as any

  await db.renameCollection('pages', 'articles', { session, dropTarget: true })
  await db.renameCollection('_pages_versions', '_articles_versions', { session, dropTarget: true }) // remove this line if you do not have versions enabled
}

export async function down({ payload, req, session }: MigrateDownArgs): Promise<void> {
  const db = payload.db.connection.db as any

  await db.renameCollection('articles', 'pages', { session, dropTarget: true })
  await db.renameCollection('_articles_versions', '_pages_versions', { session, dropTarget: true }) // remove this line if you do not have versions enabled
}

DanRibbens avatar May 22 '25 19:05 DanRibbens