Fetching prev/next posts #306
-
QuestionHas anyone needed to fetch neighboring documents of a specific document? How have you implemented this? I think my problem is when I am querying the first / last post. If I'm on the last post, the next post should be the first post. My attemptI found a few people online who were using the following mongoose queries to solve this And I attempted to wire it up with payload, but am not sure if I am missing something? import payload from 'payload';
import { BeforeReadHook } from 'payload/dist/collections/config/types';
export const appendPrevNextDoc: BeforeReadHook = async ({ doc, req, query }) => {
if (req.query && req.query.appendPrevNextDoc) {
try {
const prev = await payload.find({
collection: 'session',
sort: '-_id',
where: {
id: {
less_than: doc.id
}
}
});
const next = await payload.find({
collection: 'session',
sort: '_id',
where: {
id: {
greater_than: doc.id
}
}
})
console.log({ prev, next });
} catch (e) {
console.log(e)
}
}
return doc;
} Other thoughtsIs it possible to access the collection Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It seems to me like your code should actually work to do what you want. Does it work, for the most part? Outside of where you're saying:
If it works up to that point, and say you are on the last post with no first post, you'd just need to fetch the first post and use that manually. If this does not work at all, it might be a lower level issue. I've never personally tried to sort on IDs but I will do some digging if this should work and does not.
You should extract your hook to be reusable by wrapping your hook in another function that accepts const pages = {
// ...
hooks: {
afterRead: [
thisHookIsReusable({ collection: 'pages' }),
]
}
} |
Beta Was this translation helpful? Give feedback.
It seems to me like your code should actually work to do what you want. Does it work, for the most part? Outside of where you're saying:
If it works up to that point, and say you are on the last post with no first post, you'd just need to fetch the first post and use that manually. If this does not work at all, it might be a lower level issue. I've never personally tried to sort on IDs but I will do some digging if this should work and does not.