Question

Query referenced entries that are referenced elsewhere

  • 4 August 2023
  • 1 reply
  • 79 views

Say I have the content types “blog” and “categories”

A blog has a reference field (multiple) to categories.

How do I fetch only the categories that is being referenced at least once?

Categories: red (referenced 2x), green (referenced 0x), blue (referenced 1x)

My expected result should return me red and blue but not green.


1 reply

Hi Kevin,

Currently, there is no direct way to obtain those result using the CDA API. However, one way you can achieve this is through the following two-step process:

  1. Fetch blogs with at least one referenced category: First, get all the blogs that have at least one referenced category. The following query will filter out all the blogs that don't have any categories attached, using the $ne query. 

    https://cdn.contentstack.io/v3/content_types/blog/entries?environment=production&locale=en-us&query={"categories": { "$ne": [] }}&include_count=true

     

  2. Extract unique category UIDs and fetch corresponding entries: Next, from the response, extract all the unique UIDs of the category entries. Then, make another API call to retrieve the entry data of the referred categories, using the $in query. 

    https://cdn.contentstack.io/v3/content_types/catagories/entries?environment=production&locale=en-us&include[]=categories&query={"uid": { "$in": ["blt630c4fc00bb50385"] }}

 

With this, you should be able to retrieve the categories that are referenced at least once. And here's an example of how these steps can be applied:

const response = {
"entries": [
{
"_version": 1,
"locale": "en-us",
"uid": "blt03df3d2b38bdc18c",
"ACL": {},
"_in_progress": false,
"categories": [
{
"uid": "blt630c4fc00bb50385",
"_content_type_uid": "catagories"
}
],
"created_at": "2023-08-09T11:37:58.177Z",
"created_by": "blt829fa9ec1c032475",
"tags": [],
"title": "blog2",
"updated_at": "2023-08-09T11:37:58.177Z",
"updated_by": "blt829fa9ec1c032475",
"publish_details": {
"environment": "blt6ec191271b8120df",
"locale": "en-us",
"time": "2023-08-09T11:38:00.424Z",
"user": "blt829fa9ec1c032475"
}
},
{
"_version": 1,
"locale": "en-us",
"uid": "blt02b3f7da05d5834a",
"ACL": {},
"_in_progress": false,
"categories": [
{
"uid": "blt630c4fc00bb50385",
"_content_type_uid": "catagories"
}
],
"created_at": "2023-08-09T11:37:40.490Z",
"created_by": "blt829fa9ec1c032475",
"tags": [],
"title": "Blog 1",
"updated_at": "2023-08-09T11:37:40.490Z",
"updated_by": "blt829fa9ec1c032475",
"publish_details": {
"environment": "blt6ec191271b8120df",
"locale": "en-us",
"time": "2023-08-09T11:37:42.633Z",
"user": "blt829fa9ec1c032475"
}
}
],
"count": 2
};

const uniqueCategoryUids = new Set();

response.entries.forEach(entry => {
entry.categories.forEach(category => {
uniqueCategoryUids.add(category.uid);
});
});

const categoryUidsArray = Array.from(uniqueCategoryUids);

console.log(categoryUidsArray); // Output: ['blt630c4fc00bb50385']

 

Reply