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?
@steadysnail You could create a beforeRead hook that sorts the document
That way whenever its read, you control the order
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;
};
@Raoul Yes the sorting would happen on the doc object to be returned
@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'
}
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.