Skip to content

About

Payload CMS plugin that automatically handles cross-collection reference cleanup on cascade deletes

Topics

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

@lizardglobal/payload-collection-references

Payload CMS plugin for automatically managing collection references on document deletion.

npm

Release

Warning

This plugin is still experimental. APIs, collection schemas, and behavior may change without a stable compatibility guarantee. Use in production with caution and pin versions deliberately.

Features

  • Auto-discover all relationship and upload fields in your collections
  • Automatically register beforeDelete hooks to cascade-delete or unlink references
  • Support for nested fields (groups, tabs, arrays)

Table of Contents

Requirements

  • Payload ^3.0.0
  • Node.js >=20

Installation

pnpm add payload-collection-references

Quick Start

Add the plugin to your payload.config.ts:

import { collectionReferencesPlugin } from 'payload-collection-references'

export default buildConfig({
  collections: [
    {
      slug: 'posts',
      fields: [
        {
          name: 'author',
          type: 'relationship',
          relationTo: 'users',
        },
        {
          name: 'heroImage',
          type: 'upload',
          relationTo: 'media',
        },
      ],
    },
  ],
  plugins: [
    collectionReferencesPlugin(),
  ],
})

That's it. The plugin auto-discovers all relationship and upload fields and registers them with a default onDelete: 'delete' strategy.

How It Works

At config initialization time, the plugin:

  1. Scans every targeted collection's field tree (including nested groups, tabs, and arrays)
  2. Discovers all relationship and upload fields with their dot-notation paths
  3. Merges explicit declarations with auto-discovered relationships
  4. Injects a beforeDelete hook on each collection that other collections reference

When a document is deleted, the hook finds all documents in referencing collections and either cascade-deletes them or unlinks the field — depending on your onDelete strategy.

Configuration

Plugin Options

collectionReferencesPlugin(options?: CollectionReferencesPluginOptions)
Option Type Description
declarations Partial<Record<CollectionSlug, CollectionReferenceDeclaration[]>> Explicit per-collection reference declarations. Keys are the collection slugs that own the declared fields.
collections CollectionSlug[] Allowlist of collection slugs to apply the plugin to. Cannot be combined with exclude.
exclude CollectionSlug[] Blocklist of collection slugs to skip. Cannot be combined with collections.
disabled boolean When true, the plugin is a no-op. Useful for environment-based toggling.

Declaration Options

type CollectionReferenceDeclaration = {
  fieldPath: string            // Dot-notation path to the relationship field
  onDelete: 'delete' | 'unlink' // What to do when the referenced document is deleted
  referencedCollection: CollectionSlug // The collection the field points to (the relationship target)
  unlinkValue?: [] | null      // Value to set when unlinking (defaults to null)
}

Examples

Apply to all collections (default)

collectionReferencesPlugin()

Allowlist specific collections

collectionReferencesPlugin({
  collections: ['posts', 'authors'],
})

Exclude specific collections

collectionReferencesPlugin({
  exclude: ['media'],
})

Explicit declarations with custom onDelete strategies

Auto-discovery defaults to onDelete: 'delete'. Use explicit declarations to override this per field:

collectionReferencesPlugin({
  declarations: {
    // "posts" owns both of these relationship fields:
    posts: [
      {
        fieldPath: 'heroImage',       // field in "posts" that references "media"
        onDelete: 'unlink',           // when the media doc is deleted, set heroImage to null
        referencedCollection: 'media',
      },
      {
        fieldPath: 'author',          // field in "posts" that references "users"
        onDelete: 'delete',           // when the user is deleted, cascade-delete their posts
        referencedCollection: 'users',
      },
    ],
  },
})

Disable per environment

collectionReferencesPlugin({
  disabled: process.env.NODE_ENV === 'test',
})

Nested field paths

The plugin supports dot-notation for fields nested inside groups or tabs:

collectionReferencesPlugin({
  declarations: {
    posts: [
      {
        fieldPath: 'seo.ogImage',     // nested inside a "seo" group, owned by "posts"
        onDelete: 'unlink',
        referencedCollection: 'media',
      },
    ],
  },
})

onDelete Strategies

Strategy Behavior
'delete' Cascade-deletes all documents in the referencing collection that point to the deleted document. Triggers their own beforeDelete hooks recursively.
'unlink' Sets the relationship field to null (or a custom unlinkValue) on all matching documents. The referencing documents are preserved.

Circular reference protection

The plugin tracks processed references per request via req.context to prevent infinite loops when collections reference each other circularly.

Advanced Usage

Using the core API directly (without the plugin)

If you need finer control, you can wire up collections manually:

import {
  withCollectionReferences,
  finalizeCollectionReferences,
} from 'payload-collection-references'

const postsCollection = withCollectionReferences(
  {
    slug: 'posts',
    fields: [
      { name: 'author', type: 'relationship', relationTo: 'users' },
    ],
  },
  [
    // Explicit declaration overriding the auto-discovered default
    { fieldPath: 'author', onDelete: 'unlink', referencedCollection: 'users' },
  ],
)

const collections = finalizeCollectionReferences([postsCollection, usersCollection])

Utility exports

import {
  buildWhereForReferences,    // Build a Payload Where clause for a set of references
  filterUploadCollections,    // Filter a collection list to only upload collections
  getCollectionConfig,        // Get a CollectionConfig by slug from a request
  getReferencesPointingTo,    // Get all registered references pointing to a collection
  getRegisteredCollectionReferences, // Get the full reference registry
  groupReferencesByCollection, // Group references by their owning collection
} from 'payload-collection-references'

Utility Function Reference

getCollectionConfig(req, collectionSlug)

Returns the CollectionConfig matching a slug, read from the Payload config resolved on the request.

getCollectionConfig(req: PayloadRequest, collectionSlug: CollectionSlug): CollectionConfig | undefined
Param Type Description
req PayloadRequest Payload request, used to access req.payload.config.collections
collectionSlug CollectionSlug Slug of the collection to look up

Returns: the matching CollectionConfig, or undefined if it doesn't exist.

const postsConfig = getCollectionConfig(req, 'posts')

groupReferencesByCollection(references)

Groups a list of registered references by their owning collection (reference.collection).

groupReferencesByCollection(
  references: RegisteredCollectionReference[]
): Map<CollectionSlug, RegisteredCollectionReference[]>
Param Type Description
references RegisteredCollectionReference[] References to group

Returns: a Map where each key is a collection slug and each value is the list of references owned by that collection.

const grouped = groupReferencesByCollection(getRegisteredCollectionReferences())
const postsRefs = grouped.get('posts')

buildWhereForReferences(references, documentId)

Builds a Payload Where clause matching any document whose reference field points to documentId. Combines multiple references with or when needed.

buildWhereForReferences(
  references: RegisteredCollectionReference[],
  documentId: string
): Where
Param Type Description
references RegisteredCollectionReference[] References whose fieldPath will be tested
documentId string ID of the target document (tested with equals)

Returns: a Where object — the single reference directly if references.length === 1, otherwise { or: [...] }.

const where = buildWhereForReferences(refs, deletedDoc.id)
const affected = await req.payload.find({ collection: 'posts', where })

getReferencesPointingTo(collectionSlug)

Filters the global reference registry down to entries whose referencedCollection matches the given slug.

getReferencesPointingTo(collectionSlug: CollectionSlug): RegisteredCollectionReference[]
Param Type Description
collectionSlug CollectionSlug The referenced collection to look up

Returns: all references (auto-discovered or declared) that point to this collection — this is what the beforeDelete hook queries to know what to cascade/unlink.

const refsToMedia = getReferencesPointingTo('media')

getRegisteredCollectionReferences()

Returns the full registry of registered references, across all collections (auto-discovered + explicit declarations, merged at init time).

getRegisteredCollectionReferences(): RegisteredCollectionReference[]

Returns: the raw list of every RegisteredCollectionReference known to the plugin. Used as the source for groupReferencesByCollection and getReferencesPointingTo.

const all = getRegisteredCollectionReferences()

filterUploadCollections(collections)

Filters a list of CollectionConfig down to upload collections only (upload: true or an upload config object). Doesn't require a req — usable at config build time.

filterUploadCollections(collections: CollectionConfig[]): CollectionConfig[]
Param Type Description
collections CollectionConfig[] List of collections to filter

Returns: the subset of collections with a truthy upload.

const uploadCollections = filterUploadCollections(payloadConfig.collections)

Note: getUploadCollectionConfigs(req) does the same thing but reads req.payload.config.collections directly — no need to pass in the list.

Debug Logging

Set DEBUG=true in your environment to enable verbose logging:

DEBUG=true pnpm dev

This logs every auto-discovered relationship, every cleanup hook invocation, and every cascade or unlink operation performed.

TypeScript

The plugin is fully typed. CollectionSlug comes from Payload and resolves against your generated payload-types.ts, so collection slugs in declarations are type-safe and autocompleted.

import type {
  CollectionReferenceDeclaration,
  CollectionReferencesPluginOptions,
  CollectionSlug,
  RegisteredCollectionReference,
} from 'payload-collection-references'

Compatibility

  • Payload CMS v3+
  • PostgreSQL and MongoDB adapters

About

Payload CMS plugin that automatically handles cross-collection reference cleanup on cascade deletes

Topics

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages