Control displayed fields in relation

Is it possible to control which fields of a relation are displayed?

If I have a Part collection, and it has a relation field parts, which is a “has many” relation to Part itself, can I display a single field such as the id?

The goal would be:

[
  {
    "id": 1,
    "name": "Foo",
    "parts": [],
    ...
  },
  {
    "id": 2,
    "name": "Bar",
    "parts": [1],
    ...
  }  
]

The goal here is to avoid unnecessary duplication of data, as I don’t need all of the relation data if I know its id and it also appears in the request.

I believe this might be possible by creating a custom view, but I’m curious if this is supported elsewhere.

It looks like this might be a viable option:

async afterFind(data) {
    for (let i in data) {
        const newParts = new Array(data[i].parts.length)
        for (let j in data[i].parts) {
            newParts[j] = data[i].parts[j].id
        }
        data[i].parts = newParts
    }
}

Let me know if there’s a better way to accomplish this, or if there are any gotchas with this method.

I would recommend a simple lodash function instead.

data.parts = _.map(data.parts, 'id');

It will return only values from ID as an array.

Also, I would recommend to make these manipulations in a custom controller find()/findOne(), as the lifecycles also affect the Admin UI results.