In my pages collection I have a slug field which is generated on submission
name: 'slug',
label: 'Slug',
type: 'text',
index: true,
admin: {
position: 'sidebar',
},
hooks: {
beforeValidate: [formatSlug(fieldToUse)],
},
In the same collection, I created a custom REST endpoint for finding by slug, it obviously returns a single document for the respective slug, but since it uses payload.find from the Local API it returns a paginated response. Is there a way to do a findOne in the Local API. What is the best approach for this?
endpoints: [
{
path: "/slug/:slug",
method: "get",
handler: async (req, res, next) => {
const data = await payload.find({
collection: 'pages',
where: {slug:{equals:req.params.slug}},
limit:1
})
if (data) {
res.status(200).send({ data });
} else {
res.status(404).send({ error: "not found" });
}
},
},
],
Oh my God, I'm just finding the documentation for using
where
in the default REST API which means I don't need my custom endpoint. That said the problem remains the same, I get a paginated response with payload's default where API also
That worked like a charm. Thank you. I still think payload Local API should add a findOne.
Can't remember particularly but I think I wrote a utility function or maybe you can find it in one of the example repos that payload is maintaining.
Change the end of your custom endpoint with
if (data.docs.length === 0) {
res.status(404).send({ error: "not found" });
} else {
res.status(200).send(data.docs[0]);
}
just send first element of array in the response, or if not exists 404
i still think it's a good case for custom endpoint, so your end user won't need to manually create query on each request and less data in the response
sorry to resurrect this old thread, but
@1066271322495266846where is the
formatSlug
function coming from?
OK, I just found a plugin that has a slug field (
https://github.com/NouanceLabs/payload-better-fields-plugin/tree/master)
checking it out now
Star
Discord
online
Get dedicated engineering support directly from the Payload team.