Issues with relationship field POST & PATCH

default discord avatar
samtietjenlast year
2
// collections/Events.ts
import { CollectionConfig } from 'payload/types';
const Events: CollectionConfig = {
  slug: 'events',
  admin: {
    defaultColumns: ['updatedAt'],
    group: 'Data'
  },
  access: {
    create: () => true,
    read: () => true,
    update: () => true,
    delete: () => true,
  },
  fields: [
    {
      name: 'name',
      type: 'text',
    },
    {
      name: 'flags',
      type: 'relationship',
      relationTo: ['flags'],
      hasMany: true,
    },
  ],
}
export default Events;

// collections/Flags.ts
import { CollectionConfig } from 'payload/types';

const Flags: CollectionConfig = {
  slug: 'flags',
  admin: {
    defaultColumns: ['updatedAt'],
    group: 'Data',
    useAsTitle: 'name',
  },
  access: {
    create: () => true,
    read: () => true,
    update: () => true,
    delete: () => true,
  },
  fields: [
    {
      name: 'name',
      type: 'text',
    },
  ],
}

export default Flags;


When I try and POST this I get a 500 error. It seems to be the correct shape according to the docs, unless I misunderstood.


"Cannot read properties of undefined (reading 'fields')"

const res = await fetch('http://localhost:3000/api/events', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ 
      name: 'My Event Name', 
      flags: ['64836183d338802ee88f6745', '64836146d338802ee88f6734'],
    })
  })


Here are what the flags look like via the api



{"id":"648765ccaa340d32a2f96455","name":"Flag A","createdAt":"2023-06-12T18:37:00.864Z","updatedAt":"2023-06-12T18:37:00.864Z"}

{"id":"648765d7aa340d32a2f9646b","name":"Flag B","createdAt":"2023-06-12T18:37:11.465Z","updatedAt":"2023-06-12T18:37:11.465Z"}


I'm sure that I'm doing something extremely dumb.

  • default discord avatar
    jarrod69420last year

    make

    relationTo

    a string instead of an array like:

    relationTo: 'flags'

    . If you leave it as an array you will have to pass:


    flags: [
      {
        relationTo: 'flags',
        value: 'id',
      }
    ]


    checkout the "Has Many" vs "Has Many - Polymorphic" section in the docs here for more info:

    https://payloadcms.com/docs/fields/relationship#how-the-data-is-saved
  • default discord avatar
    samtietjenlast year

    Gosh dang it, I knew it was going to be dumb. Thanks @jarrod69420 !

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.