如何使用猫鼬获取当前项目的下一个和上一个项目 [英] How to fetch next and previous item of the current one with Mongoose
问题描述
我有一个博客.在个人帖子页面上,我想显示一个指向上一篇文章的链接,如果有,则在底部发布下一篇文章.链接应该是特定帖子的标题.
I have a blog. On the individual post page I want to display a link to the previous, and if there is one, next post published in the bottom. The link should be the title of the specific post.
如何使用 Mongoose 以最简单的方式做到这一点?
How do I do that the simplest way with Mongoose?
我当前的控制器如下所示:
My current controller looks like this:
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,所以我们它包含发布日期,我可以对其进行排序
I suppose that _id is mongo ObjectId, so we it contains post date and i can sort on it
让我们考虑一下我已经打开了当前帖子,id 等于 ObjectId("43cc63093475061e3d95369d")
(而不是这个,我将使用 curId
),我需要知道下一个一个和以前.还让我们考虑一下我们需要按创建日期降序排列所有帖子:
Lets consider that i have opened current post with id equal to ObjectId( "43cc63093475061e3d95369d")
(instead of this i will use curId
) and i need to know next one and previous. Also lets consider that we need get all posts one by one ordered by created date descending:
获取下一篇你可以喜欢的帖子:
Get next post you can like this:
db.posts.find({_id: {$gt: curId}}).sort({_id: 1 }).limit(1)
获取以前的帖子,您可以这样:
Get previous post you can like this:
db.posts.find({_id: {$lt: curId}}).sort({_id: -1 }).limit(1)
一些事情:
- 如果你不使用 mongodb
ObjectId
上面的代码对你不起作用,但你仍然可以使用postDate
代替 id 和当前 post postDate 代替curId
. - 获取下一篇/上一篇文章时要注意顺序,要检索下一篇文章需要按升序排序,要检索上一篇文章需要按降序排序.
- 我对 mongoose 不熟悉,所以上面的脚本是 mongodb shell 脚本.
- If you don't use mongodb
ObjectId
above code will not work for you, but you can still usepostDate
instead of id and current post postDate instead ofcurId
. - Take care about order when getting next/prev posts, to retrieve next post you need sort asc, to retrieve prev post you need sort desc.
- I am not familiar with mongoose, so above scripts is mongodb shell scripts.
这篇关于如何使用猫鼬获取当前项目的下一个和上一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!