问题
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?
回答1:
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.getEntry({
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.
来源:https://stackoverflow.com/questions/54275516/how-to-fetch-a-single-entry-from-contentful-and-query-by-field-value