Mikael Vesavuori
Mikael Vesavuori

Reputation: 23

Contentful JS: Unable to retrieve entries by matching Reference field

I am using Contentful's Javascript API to build a project. Currently, I'm having an issue where I get "undefined" as a return for the following call.

const query = {
  content_type: "vehicle",
  include: 2,
  select: "fields",
  "fields.site.fields.siteName[match]": id
};

I've set up "vehicle" as a model which uses a "site" reference with names, addresses and so forth. It seems to be possible to use [exist] on the first level, like

"fields.site[exists]": true

which works, but is unsatisfactory for what I need.

What I need are any Vehicles that belong to a named Site. Obviously, I've made sure to add the relevant content, and I can indeed see the data when omitting the "fields.site.fields..." line. For security purposes, I would very much not have vehicles for other sites showing up in the response.

Am I missing something? Upping the "include" level does not do anything either.

Upvotes: 1

Views: 2234

Answers (1)

stefan judis
stefan judis

Reputation: 3879

👋🏻

I believed you didn't see one sentence in the docs.

Second is fields.brand.sys.contentType.sys.id=sFzTZbSuM8coEwygeUYes which you use to to filter on fields of entries from content type 2PqfXUJwE8qSYKuM0U6w8M.

So basically to make your query work you have also to define the content type of the entry your search query is matching against.

I quickly prototyped your case in Node.js.

const { createClient } = require('contentful');
const client = createClient({
  space: '...',
  accessToken: '...'
});

client.getEntries({
  content_type: 'vehicle',
  select: 'fields',
  // this is the line you're missing
  'fields.site.sys.contentType.sys.id': 'site',
  'fields.site.fields.siteName': 'vw-site'
}).then(({items}) => {
  console.log(items);
}).catch(e => console.log(e));

You can find a detailed example in the docs

Hope that helps :)

Upvotes: 2

Related Questions