如何使用Mongoose获取当前项目的下一个和上一个项目

How to fetch next and previous item of the current one with Mongoose

本文关键字:项目 下一个 上一个 何使用 Mongoose 获取      更新时间:2023-09-26

我有一个博客。在个人帖子页面上,我想显示上一篇文章的链接,如果有,下一篇文章会在底部发布。链接应该是特定帖子的标题。

如何使用Mongoose以最简单的方式做到这一点?

我当前的控制器是这样的:

Post.findOne { slug : req.params.slug }, (err, post) ->
  res.render "blog/show.jade", locals: title: "This post", post: post

模式看起来是这样的:

PostSchema = new Schema(
  title:
    type: String
    required: true
    index: true
  preamble: String
  body: String
  slug: String
  createdAt: Date
  updatedAt: Date
)

所以假设您有这样的模式:

{
 _id,
 text    
}

我假设_id是mongo ObjectId,所以它包含发布日期,我可以对它进行排序

让我们考虑一下,我已经打开了id等于ObjectId( "43cc63093475061e3d95369d")的当前帖子(而不是使用curId),我需要知道下一个和上一个。还让我们考虑一下,我们需要按照创建日期降序逐一获取所有帖子:

获得下一个你可以喜欢的帖子:

db.posts.find({_id: {$gt: curId}}).sort({_id: 1 }).limit(1)

获取上一篇你可以喜欢的帖子:

db.posts.find({_id: {$lt: curId}}).sort({_id: -1 }).limit(1)

很少的事情:

  1. 如果你不使用mongodb ObjectId,上面的代码将不适用于你,但你仍然可以使用postDate代替id,使用currentpostpostDate代替curId
  2. 获取下一篇/上一篇帖子时要注意顺序,检索下一篇帖子需要排序asc,检索上一篇文章需要排序desc
  3. 我不熟悉mongoose,所以上面的脚本是mongodbshell脚本

查找上一项:

Post.findOne({_id: {$lt: curId}}).sort({_id: -1}).exec(cb)

查找下一项:

Post.findOne({_id: {$gt: curId}}).sort({_id: 1}).exec(cb)