npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@lizardglobal/payload-collection-references

v1.0.2

Published

A Payload CMS plugin that adds support for collection references.

Downloads

330

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)

| 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