Search code examples
javascriptnode.jscontentful

How to retrieve linked fields in Contentful query


I'm using Contentful and have a content model which uses a series of related fields. I am querying my content in NodeJS using the JS api. If I call get entries, like so

contentfulClient.getEntries({
    content_type: 'homePage'
})

it fetches all the content of type homePage, and includes the actual field data for each related field, like so

"subField": {
        "sys": {
            "space": {
                "sys": {
                    "type": "Link",
                    "linkType": "Space",
                    "id": "#######"
                }
            },
            "id": "#######",
            "type": "Entry",
            "createdAt": "2017-03-10T15:58:25.697Z",
            "updatedAt": "2017-03-10T15:58:25.697Z",
            "revision": 1,
            "contentType": {
                "sys": {
                    "type": "Link",
                    "linkType": "ContentType",
                    "id": "homeSubField"
                }
            },
            "locale": "en-GB"
        },
        "fields": {
            "category": {
                "sys": {
                    "type": "Link",
                    "linkType": "Entry",
                    "id": "#######"
                }
            },
            "subFieldContent": "Some field content"
        }
    },

However, if I call a specific entry with an ID, like

contentfulClient.getEntry('1234567890')

Then each linked field is just returned as a reference with an ID, like

"subField": {
            "sys": {
                "type": "Link",
                "linkType": "Entry",
                "id": "#######"
            }
        },

How can I get the full text when calling getEntry, like I do with getEntries?


Solution

  • Unfortunately Contentful does not include referenced content when fetching a content item by id directly. One way around this is to instead use the getEntries method, but filter by sys.id. That way you'll get the same entry back, although in an array, but it will also include referenced content.

    contentfulClient.getEntries({
       content_type: 'homePage',
       sys.id: '1234567890'
    })
    

    This also results in a single request instead of multiple as you would end up with when using the GetEntry method and then resolving each referenced content item manually.