4

I am trying to retrieve a single entry based on the name custom field of my entry.

I have tried using the JS SDK with various options:

client.getEntry("entryID")
    // .where("content_type", "Restaurant")
    // .where("fields.name[match]", "RestaurantName")
    // .all()
    .then(data => console.log('data', data))
    .catch(err => console.log('err', err))

But based on the errors back, it's suggesting I can only use .getEntry and pass in the entry ID.

I also looked at making an HTTP request with axios but faced a similar issue with only being able to retrieve either a full list of entries or filtered based on the entry ID.

Is there a away I can fetch by `field.name === "Slug" or some other custom field I have added?

Stretch0
  • 8,362
  • 13
  • 71
  • 133

1 Answers1

5

Currently the only way to get an entry using getEntry, is to pass in the sys.id value. We use a single controller anytime that we request anything from Contentful. This allows us to set error messages, transform the data returned into the format we want etc. We added to the controller our own getEntry helper function that can be called by

contentfulController.getEntries({
   content_type: 'indexPage',
   'fields.slug[match]': slug,
   include: 3,
   locale: language,
});

Then inside our own getEntry function we grab the first one in the array, and return the object since we always know we will be returning one.

However its important to note that this can cause issues if you have sub strings in the slug. Lets say you have two items with the slugs:

/resource
/resourcelisting

If you query 'fields.slug[match]': '/resource', it will return both items in the results so you should also check which one has the actual slug you want, not part of it.

Jesse Reza Khorasanee
  • 3,140
  • 4
  • 36
  • 53
  • 1
    Thanks for this, getEntry didn't work but getEntries() with that query object did – alana314 Dec 02 '19 at 18:38
  • Additionally, looking at the TypeScript definitions: `getEntry(id: string, query?: any): Promise>` requires the `sys.id`. Only the `getEntries(query?: any): Promise>` allows for querying without a `sys.id`. – Advena Jun 20 '23 at 07:24