LizardGlobalGH

payload collection references

by LizardGlobalGH
Databases & data
v3
^3.84.1
MIT

Overview

Summary generated from the README

Scans collections for relationship and upload fields, including nested groups, tabs and arrays, and registers beforeDelete hooks on referenced collections. When a document is deleted, referencing documents are either cascade-deleted or have the field unlinked. Configured through plugin options for allowlists, exclusions and per-field declarations. Marked experimental; works with PostgreSQL and MongoDB adapters.

Features

  • Auto-discovers relationship and upload fields, including nested ones
  • Per-field onDelete strategy: delete or unlink
  • Custom unlink value, either null or an empty array
  • Collection allowlist, exclude list and disabled toggle
  • Circular reference protection tracked per request
  • Utility exports for reference registry lookups and where-clause building

Use cases

  • Remove posts automatically when their author user is deleted
  • Clear hero image fields when a media file is deleted instead of leaving dangling references
  • Keep relationships consistent across many collections without writing custom delete hooks

From the author

A Payload CMS plugin that adds support for collection references.

Installation

npm i @lizardglobal/payload-collection-references

2

Stars

0

Forks

0

Open Issues

4 months ago

Last Updated

11

Weekly Downloads

v1.0.2

npm Version

76.6 KB

Unpacked Size

0

Dependencies

GitHub stars

20 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20262
Dec 4, 20262
Dec 3, 20262
Dec 2, 20262
Dec 1, 20262
Nov 30, 20262
Nov 29, 20262
Nov 28, 20262
Nov 27, 20262
Nov 26, 20262
Nov 25, 20262
Nov 24, 20262
Nov 23, 20262
Nov 22, 20262
Nov 21, 20262
Nov 20, 20262
Nov 19, 20262
Nov 18, 20262
Nov 17, 20262
Nov 16, 20262
Nov 15, 20262
Nov 14, 20262
Nov 13, 20262
Nov 12, 20262
Nov 11, 20262
Nov 10, 20262
Nov 9, 20262
Nov 8, 20262
Nov 7, 20262
Nov 6, 20262
Nov 5, 20262
Nov 4, 20262
Nov 3, 20262
Nov 2, 20262
Nov 1, 20262
Oct 31, 20262
Oct 30, 20262
Oct 29, 20262
Oct 28, 20262
Oct 27, 20262
Oct 26, 20262
Oct 25, 20262
Oct 24, 20262
Oct 23, 20262
Oct 22, 20262
Oct 21, 20262
Oct 20, 20262
Oct 19, 20262
Oct 18, 20262
Oct 17, 20262
Oct 16, 20262
Oct 15, 20262
Oct 14, 20262
Oct 13, 20262
Oct 12, 20262
Oct 11, 20262
Oct 10, 20262
Oct 9, 20262
Oct 8, 20262
Oct 7, 20262
Oct 6, 20262
Oct 5, 20262
Oct 4, 20262
Oct 3, 20262
Oct 2, 20262
Oct 1, 20262
Sep 30, 20262
Sep 29, 20262
Sep 28, 20262
Sep 27, 20262
Sep 26, 20262
Sep 25, 20262
Sep 24, 20262
Sep 23, 20262
Sep 22, 20262
Sep 21, 20262
Sep 20, 20262
Sep 19, 20262
Sep 18, 20262
Sep 17, 20262
Sep 16, 20262
Sep 15, 20262
Sep 14, 20262
Sep 13, 20262
Sep 12, 20262
Sep 11, 20262
Sep 10, 20262
Sep 9, 20262
Sep 8, 20262
Sep 7, 20262
Sep 6, 20262
npm weekly downloads

7−2 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 20267
Dec 4, 20268
Dec 3, 20269
Dec 2, 20265
Dec 1, 20267
Nov 30, 20268
Nov 29, 20267
Nov 28, 20266
Nov 27, 20265
Nov 26, 20266
Nov 25, 20266
Nov 24, 20264
Nov 23, 20263
Nov 22, 20265
Nov 21, 20265
Nov 20, 20265
Nov 19, 20263
Nov 18, 20265
Nov 17, 20264
Nov 16, 20264
Nov 15, 20263
Nov 14, 20264
Nov 13, 20266
Nov 12, 20266
Nov 11, 20264
Nov 10, 20266
Nov 9, 20266
Nov 8, 20267
Nov 7, 20268
Nov 6, 20267
Nov 5, 20268
Nov 4, 20268
Nov 3, 20268
Nov 2, 20269
Nov 1, 20267
Oct 31, 20265
Oct 30, 20264
Oct 29, 20263
Oct 28, 20263
Oct 27, 20261
Oct 26, 20263
Oct 25, 20263
Oct 24, 20263
Oct 23, 20263
Oct 22, 20266
Oct 21, 20266
Oct 20, 20266
Oct 19, 20263
Oct 18, 20265
Oct 17, 20265
Oct 16, 20265
Oct 15, 20262
Oct 14, 20262
Oct 13, 20262
Oct 12, 20262
Oct 11, 20261
Oct 10, 20261
Oct 9, 20261
Oct 8, 20261
Oct 7, 20261
Oct 6, 20264
Oct 5, 20264
Oct 4, 20265
Oct 3, 20267
Oct 2, 20267
Oct 1, 20267
Sep 30, 20269
Sep 29, 20266
Sep 28, 20267
Sep 27, 20265
Sep 26, 20267
Sep 25, 20267
Sep 24, 20267
Sep 23, 20267
Sep 22, 20268
Sep 21, 20269
Sep 20, 20269
Sep 19, 20265
Sep 18, 20265
Sep 17, 20266
Sep 16, 20264
Sep 15, 20266
Sep 14, 20264
Sep 13, 20264
Sep 12, 20265
Sep 11, 20265
Sep 10, 20266
Sep 9, 20267
Sep 8, 20265
Sep 7, 20267
Sep 6, 20269

Each point is npm's rolling 7-day download count.

Health Score

53/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1272063083-root.svg)](https://payloaddirectory.dev/plugins/1272063083-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1272063083-root"><img src="https://payloaddirectory.dev/badge/1272063083-root.svg" alt="Payload Directory"></a>
Updated Aug 4, 2026Created Jun 17, 2026Published Aug 4, 2026

README

@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)
OptionTypeDescription
declarationsPartial<Record<CollectionSlug, CollectionReferenceDeclaration[]>>Explicit per-collection reference declarations. Keys are the collection slugs that own the declared fields.
collectionsCollectionSlug[]Allowlist of collection slugs to apply the plugin to. Cannot be combined with exclude.
excludeCollectionSlug[]Blocklist of collection slugs to skip. Cannot be combined with collections.
disabledbooleanWhen 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

StrategyBehavior
'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
ParamTypeDescription
reqPayloadRequestPayload request, used to access req.payload.config.collections
collectionSlugCollectionSlugSlug 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[]>
ParamTypeDescription
referencesRegisteredCollectionReference[]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
ParamTypeDescription
referencesRegisteredCollectionReference[]References whose fieldPath will be tested
documentIdstringID 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[]
ParamTypeDescription
collectionSlugCollectionSlugThe 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[]
ParamTypeDescription
collectionsCollectionConfig[]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

Similar plugins