select next and previous records in Sequelize based on createdAt

Viewed 230

What I want: fetch one record from the database based on its ID (UUID) and retrieve next and previous records too

Associations: posts N:M categories, posts 1:N comments, posts N:1 users, posts N:M tags, posts 1:N post_views

Current solution:

const post = await PostModel.findByPk(id, {
    include: [
      { model: CategoryModel, attributes: ['title'] },
      { model: TagModel },
      { model: CommentModel, include: { model: UserModel } },
      { model: PostViewModel },
      { model: UserModel, attributes: ['fullname', 'id', 'avatar'] }
    ]
  });
const nextPost = await PostModel.findOne({
  where: { createdAt: {
    [Op.gt]: post.createdAt
  }}
const prevPost = await PostModel.findOne({
  where: { createdAt: {
    [Op.lt]: post.createdAt
  }}

});

but I think this is not efficient and good.

0 Answers
Related