apostrophe-cms

How to properly handle joinByArrayReverse with multiple types?


I have the piece type project which has an _author, which can be of two different types:

module.exports = {
  extend: 'apostrophe-pieces',
  name: 'project',
  label: 'Project',
  pluralLabel: 'Projects',
  addFields: [
    {
      label: 'Creator',
      help: 'Person or collective who created the project.',
      name: '_author',
      idsField: 'creatorIds',
      type: 'joinByArray',
      withType: [
        'person',
        'organization'
      ],
      filters: {
        projection: {
          _url: 1,
          title: 1,
        }
      },
      required: true
    },
    ...

This works perfectly fine.

On the other hand, I wish to create a reverse relationship for the authors so there can be a way to obtain their projects.

module.exports = {
  extend: 'apostrophe-pieces',
  name: 'person',
  label: 'Person',
  pluralLabel: 'People',
  addFields: [
    {
      name: '_projects',
      reverseOf: '_author',
      idsField: 'creatorIds',
      type: 'joinByArrayReverse',
      withType: 'project',
      filters: {
        projection: {
          _url: 1,
          title: 1,
        }
      },
    },
    ...

This compiles fine, however as soon at the site loads, this error is thrown:

Error: I think you forgot to set idField or idsField, or you set the wrong one (use idField for byOne, idsField for byArray)

What is the appropriate strategy to handle this case then?


Solution

  • Very late to contributing, but this just happened to me. The issue can be reproduced by first having the piece type be joinbyOne, creating a few pieces, and then switching the join to joinByArray.

    When I did that, I had the error you highlighted. I fixed it by removing the reverseOf field

    In your case:

      name: '_projects',
      idsField: 'creatorIds',
      type: 'joinByArrayReverse',
      withType: 'project',
      filters: {
        projection: {
          _url: 1,
          title: 1,
        }
      },
    

    In the documentation it states that the field is optional as long as there's only one join with the piece type. If you have more than one join with the person piece type, this solution may not work. I'm still unsure why removing it solved the issue, but it worked.