Bug:
Versions collection fails with "Cast to Embedded failed" when using localized arrays containing blocks (MongoDB)
Environment:
- Payload: 3.61.1 (persists from 3.60.0)
- Database: MongoDB
Issue:
Collections with versions: { drafts: true } fail to save versions when localized arrays contain blocks fields. Main collection saves successfully, but version creation throws MongoDB validation errors.
Error:
_contents_versions validation failed: version: Cast to Embedded failed for value "{...}" (type Object) at path "version" because of "TypeError"
Reproduction:
- Enable versions with drafts on a collection
- Create localized array field containing blocks:
{
name: 'fields',
type: 'array',
localized: true,
fields: [
{
name: 'value',
type: 'blocks',
blocks: [Text, Email, Relationship] // Any blocks
}
]
}
- Create document - main collection saves fine, versions collection fails
Root Cause Analysis:
The issue occurs in the version creation pipeline due to block reference loss during field flattening:
- Field Context Loss: In buildVersionCollectionFields() (packages/payload/src/versions/buildCollectionFields.ts:22-25), the version field structure is created using:
fields: collection.fields.filter((field) => !('name' in field) || field.name !== 'id')
- This filtering process creates new field references that lose the original block definitions.
- Block Resolution Failure: During version processing, stripFields() in packages/db-mongodb/src/utilities/transform.ts:369 attempts:
maybeBlock = field.blocks.find((each) => each.slug === data.blockType)
- But field.blocks is now empty/undefined because the version field structure doesn't preserve the original blocks array.
- Data Corruption: Failed block lookup causes fieldData[i] = null (line 375), corrupting the document structure and triggering MongoDB's "Cast to Embedded failed" validation error.