If you’re using the incredibly lean, headless content management system, or CMS, Contentful, you may have seen this error:
“When searching on references you must specify the Content Type of the reference. Please send a Content Type id as a query parameter.”
Background
I wanted to use a different model type for category than I used for tags, short-text list, because the reference type allows you to control and manage category names outside of the blog post model. If you want to query entries that have the type short-text list, you can write a function like this:
getBlogPostsByTag(tag:string):Promise<BlogPost[]> {
return this.blogService.getEntries({
content_type: this.contentTypeIdBlogPost,
'fields.tags': tag,
'order': '-fields.publishDate'
})
.then(res => res)
.catch(error => error);
}
Solution
If you want to query entries that have a reference data type, you have to specify the content type of the reference data. You can resolve the above error by writing a function like this:
getBlogPostsByCategory(category:string):Promise<BlogPost[]> {
return this.blogService.getEntries({
content_type: this.contentTypeIdBlogPost,
'fields.category.sys.contentType.sys.id':
this.contentTypeIdBlogCategory,
'fields.category.fields.name': category,
'order': '-fields.publishDate'
})
.then(res => res)
.catch(error => error);
}
Note: Contentful allows you to query reference types only if they contain one field. For example, my category only has the name field.
Also, to future-proof any changes to the content type IDs by identifying them only in one place (technically two, one for dev and one for prod), I am storing those values in my app’s environment files. So make sure you substitute those variables with your content type IDs.