sorting relationship field

default discord avatar
steadysnail
2 months ago
4

I have a collection that has the property "defaultSort": "-id", and is rendering as expected, in descending order based on the "id." However, I'm referencing this same collection in a standard relationship field in a different collection, and it is being displayed in ascending order. Is there a way I can sort the relationship field?

  • default discord avatar
    notchr
    2 months ago

    @steadysnail You could create a beforeRead hook that sorts the document



    That way whenever its read, you control the order

  • default discord avatar
    Raoul
    2 months ago

    is this stilla active?




    const beforeReadHook: CollectionBeforeReadHook = async ({


    doc, // full document data


    req, // full express request


    query, // JSON formatted query


    }) => {


    //WOULD YOU DO THE SORTING HERE?


    return doc;


    };

  • default discord avatar
    notchr
    2 months ago

    @Raoul Yes the sorting would happen on the doc object to be returned

  • default discord avatar
    steadysnail
    last month

    @notchr Thanks for replying, and please excuse my late reply. Trying to sort via a beforeRead hook doesn't seem to work because the hook runs for every record in the collection instead of once for all records. When I console.log ("doc", doc) in the beforeReadHook I get the following:


    doc: {
      id: '0.0.27',
      sortableTag: 1000100028000,
      createdAt: '2023-08-02T18:42:36.444Z',
      updatedAt: '2023-08-02T18:42:36.444Z'
    }
    doc: {
      id: '0.0.26',
      sortableTag: 1000100027000,
      createdAt: '2023-08-02T18:42:36.444Z',
      updatedAt: '2023-08-02T18:42:36.444Z'
    }
    doc: {
      id: '0.0.25',
      sortableTag: 1000100026000,
      createdAt: '2023-08-02T18:42:36.448Z',
      updatedAt: '2023-08-02T18:42:36.448Z'
    }
    doc: {
      id: '0.0.24',
      sortableTag: 1000100025000,
      createdAt: '2023-08-01T14:43:42.234Z',
      updatedAt: '2023-08-01T14:43:42.234Z'
    }
    doc: {
      id: '0.0.23',
      sortableTag: 1000100024000,
      createdAt: '2023-08-01T14:43:42.234Z',
      updatedAt: '2023-08-01T14:43:42.234Z'
    }
    doc: {
      id: '0.0.22',
      sortableTag: 1000100023000,
      createdAt: '2023-08-01T14:43:42.234Z',
      updatedAt: '2023-08-01T14:43:42.234Z'
    }
Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

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